赛派号

光纤和宽带哪种好用 PHP Cheatsheet

PHP Cheatsheet Previous Next

This PHP cheatsheet provides a quick overview and revision of all concepts of PHP programming and is helpful for students and developers as well. If you are preparing for any exam or an interview, we recommend going through this cheatsheet to learn and enhance your PHP skills.

Script Syntax

Use the below syntax to write a PHP script −

You can also use its short echo tag, which is −

Printing "Hello, World!"

You can print "Hello, World!" in PHP using the PHP echo statement.

Comments

PHP provides single and multiline comments. Where a single-line comment starts with # or // and a multiline comment is enclosed within /* and */.

1. Single-line comment // Write single-line comment here # Write single-line comment here 2. Multi-line comment /* You can write multi-line comment like this*/ Variables

PHP variables store data and information. A variable can be declared using the dollar ($) sign followed by the variable name.

Printing Variables

You can use the PHP echo statement to print variables.

Printing Newline

You can print a newline using the echo statement by using the "\n" to print a newline in PHP. And, to display a newline in the browser, use the "" tag.

1. Printing on Console 2. Printing On Web Browser Printing Text

You can print text by using the following functions −

echo print printf print_r 1. Printing Using echo

Use echo to print one or more strings.

2. Printing Using print

Use print to print one single string.

3. Printing Using printf

Use printf to print formatted string.

4. Printing using print_r

Use print_r for debugging and displays human-readable information about variables, particularly arrays or objects.

Embedding HTML elements with Text

You can embed HTML elements with text using the echo and print function.

Embedding PHP in HTML

You can also embed PHP inside HTML elements.

Combining PHP variables with HTML

You can include PHP variables within HTML elements as follows −

Data Types 1. String

String data type represents a sequence of characters.

$str1 = "Hello, World!"; $str2 = 'PHP Data Types'; 2. Integer

Integer data type represents non-decimal numbers between -2,147,483,648 and 2,147,483,647 (on 32-bit systems).

$int = 42; 3. Float (Double)

Float (double) data type represents numbers with a fractional part.

$float = 3.14; 4. Boolean

Boolean data type represents two possible values: TRUE or FALSE.

$is_admin = true; $is_guest = false; 5. Array

PHP array type stores multiple values in a single variable.

// Indexed array $cities = array("Hyderabad", "Bangalore", "Mangalore"); // Associative array $person = array("name" => "Kelly Hu", "age" => 22); 6. Object

An array type is an instance of a class.

7. NULL

The NULL type represents a variable with no value.

$var = null; Strings

PHP strings are sequences of characters enclosed with either single quotes ('Hello') or double quotes ("Hello").

1. Creating and Printing String

You can create a string variable by assigning a string to a variable and print it by using the echo statement.

2. String Concatenation

The dot (.) operator can be used to concatenate two strings.

3. String Length

You can use the strlen() method to get the string length.

$len = strlen("Hello"); // Output: 5 4. String Functions

Some of the commonly used string functions that are used for various string operations are as follows −

Function Name Use Example strlen() Returns the length of a string. $str = "Hello World!"; echo strlen($str); str_word_count() Returns the number of words in a string. $str = "Hello World!"; echo str_word_count($str); strrev() Returns the reversed string. $str = "Hello"; echo strrev($str); strpos() Returns the position of the first occurrence of a substring. $str = "Hello World!"; echo strpos($str, "World"); str_replace() Replaces some characters with others in a string. $str = "Hello World!"; echo str_replace("World", "Harry", $str); strtolower() Returns the lowercase converted string. $str = "HELLO WORLD!"; echo strtolower($str); strtoupper() Returns the uppercase converted string. $str = "hello world!"; echo strtoupper($str); trim() Removes whitespace or predefined characters from both ends. $str = " Hello World! "; echo trim($str); ltrim() Removes whitespace or predefined characters from the left side. $str = " Hello World! "; echo ltrim($str); rtrim() Removes whitespace or predefined characters from the right side. $str = " Hello World! "; echo rtrim($str); str_repeat() Repeats a string a specified number of times. $str = "Hi! "; echo str_repeat($str, 3); substr() Returns a part of a string. $str = "Hello World!"; echo substr($str, 6, 5); ucfirst() Returns the string hing the first character of a string to uppercase. $str = "hello world!"; echo ucfirst($str); ucwords() Returns the string hing the first character of each word in a string to uppercase. $str = "hello world!"; echo ucwords($str); strcmp() Compares two strings (case-sensitive). $str1 = "Hello"; $str2 = "hello"; echo strcmp($str1, $str2); strcasecmp() Compares two strings (case-insensitive). $str1 = "Hello"; $str2 = "hello"; echo strcasecmp($str1, $str2); str_shuffle() Randomly shuffles the characters of a string. $str = "Hello"; echo str_shuffle($str); number_format() Formats a number with grouped thousands. $num = 1234567.89; echo number_format($num, 2);

You can go through our reference page to read more about these methods: PHP String Functions Reference.

Escape Characters

PHP supports the following escape characters −

Escape Character Description \\ Backslash \' Single quote \" Double quote \n New line \r Carriage return \t Horizontal tab \b Backspace \f Form feed \v Vertical tab \0 Null character \xHH Hexadecimal value (HH is the hex code) \u{HHHH} Unicode character (PHP 7.2+) Example of Escape Characters Operators

PHP operators are the symbols used to perform operations on variables and values. The following are the different types of operators −

List of All Operators Operator Type Operator Description Example Arithmetic + Addition 5 + 3 (outputs 8) - Subtraction 5 - 3 (outputs 2) * Multiplication 5 * 3 (outputs 15) / Division 5 / 2 (outputs 2.5) % Modulus (remainder) 5 % 2 (outputs 1) Assignment = Assigns value $x = 5; += Adds and assigns $x += 3; (same as $x = $x + 3;) -= Subtracts and assigns $x -= 2; (same as $x = $x - 2;) *= Multiplies and assigns $x *= 2; (same as $x = $x * 2;) /= Divides and assigns $x /= 2; (same as $x = $x / 2;) %= Modulus and assigns $x %= 3; (same as $x = $x % 3;) Comparison == Equal (value) ($x == $y) === Identical (value and type) ($x === $y) != Not equal ($x != $y) !== Not identical (value or type) ($x !== $y) Greater than ($x > $y) = $y) Logical && Logical AND ($x && $y) || Logical OR ($x || $y) ! Logical NOT !$x String . Concatenation (combines two strings) $str = "Hello" . " World"; Increment/Decrement ++ Increment (adds one) ++$x or $x++ -- Decrement (subtracts one) --$x or $x-- Example of PHP Operators Conditional Statements

PHP conditional statements are used to execute code based on conditions. The conditional statements are −

if if else Multiple if else Nested if else switch 1. The if Statement 2. The if else Statement 3. Multiple if else Statement 4. Nested if else Statement 5. The switch Statement Math Functions

PHP math functions are used for performing various mathematical operations. The following are the math functions −

Function Example abs() echo abs(-5); // Outputs: 5 ceil() echo ceil(4.3); // Outputs: 5 floor() echo floor(4.7); // Outputs: 4 round() echo round(4.5); // Outputs: 5 max() echo max(1, 3, 2); // Outputs: 3 min() echo min(1, 3, 2); // Outputs: 1 pow() echo pow(2, 3); // Outputs: 8 sqrt() echo sqrt(16); // Outputs: 4 rand() echo rand(1, 100); // Outputs: random number mt_rand() echo mt_rand(1, 100); // Outputs: random number sin() echo sin(deg2rad(90)); // Outputs: 1 cos() echo cos(deg2rad(180)); // Outputs: -1 tan() echo tan(deg2rad(45)); // Outputs: 1 deg2rad() echo deg2rad(180); // Outputs: 3.14159 rad2deg() echo rad2deg(M_PI); // Outputs: 180 Constants

PHP constants are the variables with a fixed value. Constants are defined using define().

Magic Constants

PHP magic constants are special constants with special meanings. The following are the magic constants −

Constant Name Description __LINE__ Current line number of the file. __FILE__ Full path and filename of the file. __DIR__ Directory of the file. __FUNCTION__ Name of the function (case-sensitive). __CLASS__ Name of the class (case-sensitive). __METHOD__ Name of the method (case-sensitive). __NAMESPACE__ Current namespace (empty if none). __TRAIT__ Name of the trait (case-sensitive). Example of Magic Constants Loops

PHP loops repeat a block of code multiple times. The following are the types of loops −

for foreach while do...while 1. The for Loop 2. The foreach Loop 3. The while Loop 4. The do...while Loop Functions

PHP functions are blocks of code that can be executed on demand. The following is an example of a simple function −

Arrays

PHP arrays are used to store multiple values of the same or different types. The following are the different types of arrays −

Indexed Associative Multidimensional 1. The Indexed Array 2. The Associative Array Global Variables - Superglobals

PHP global variables (also known as superglobals) are built-in global arrays that are used to provide information or track variables. The superglobals are:

Superglobal Description $_GET Collects data sent via URL parameters in a GET request. $_POST Collects data sent via HTTP POST method. $_REQUEST Collects data from $_GET, $_POST, and $_COOKIE. $_SESSION Stores data across pages for individual users. $_COOKIE Stores data on the clients browser as small text files. $_FILES Manages file uploads. $_ENV Holds environment variables. $_SERVER Contains information about server and execution environment. $_GLOBALS Accesses all global variables in the PHP script. Regular Expressions

PHP regular expressions are the patterns used for matching strings.

1. Validate an Email Address 2. Validate a Phone Number

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至lsinopec@gmail.com举报,一经查实,本站将立刻删除。

上一篇 没有了

下一篇没有了