What is PHP?
<?php
// PHP code goes here
?>
// This is a single-line comment
# This is also a single-line comment
<?php
$txt = "Hello world!";
$x = 5;
$y = 10.5;
?>
global $x, $y;
static $x = 0;
echo "<h2>PHP is Fun!</h2>";
print "I'm about to learn PHP!";
PHP String
$x = "Hello world!";
PHP Integer
$x = 5985;
PHP Boolean
$x = true;
PHP Array
$cars = array("Volvo","BMW","Toyota");
PHP Object
class Car {
public $color;
public $model;
public function __construct($color, $model) {
$this->color = $color;
$this->model = $model;
}
$myCar = new Car("black", "Volvo");
PHP NULL Value
$x = null;
strlen() - Return the Length of a String
echo strlen("Hello world!"); // outputs 12
str_word_count() - Count Words in a String
echo str_word_count("Hello world!"); // outputs 2
strrev() - Reverse a String
echo strrev("Hello world!"); // outputs !dlrow olleH
strpos() - Search For a Text Within a String
echo strpos("Hello world!", "world"); // outputs 6 otherwise FALSE
str_replace() - Replace Text Within a String
echo str_replace("world", "Dolly", "Hello world!"); // outputs Hello Dolly!
echo(pi()); // returns 3.1415926535898
echo(min(0, 150, 30, 20, -8, -200)); // returns -200
echo(max(0, 150, 30, 20, -8, -200)); // returns 150
echo(abs(-6.7)); // returns 6.7
echo(sqrt(64)); // returns 8
echo(round(0.60)); // returns 1
echo(rand());
Syntax
define(name, value, case-insensitive)
Example
define("GREETING", "Welcome to W3Schools.com!", true);
echo greeting;
Operator | Name | Example | Result |
---|---|---|---|
+ | Addition | $x + $y | Sum of $x and $y |
- | Subtraction | $x - $y | Difference of $x and $y |
* | Multiplication | $x * $y | Product of $x and $y |
/ | Division | $x / $y | Quotient of $x and $y |
% | Modulus | $x % $y | Remainder of $x divided by $y |
** | Exponentiation | $x ** $y | Result of raising $x to the $y'th power |
Assignment | Same as... | Description |
---|---|---|
x = y | x = y | The left operand gets set to the value of the expression on the right |
x += y | x = x + y | Addition |
x -= y | x = x - y | Subtraction |
x *= y | x = x * y | Multiplication |
x /= y | x = x / y | Division |
x %= y | x = x % y | Modulus |
Operator | Name | Example | Result |
---|---|---|---|
== | Equal | $x == $y | Returns true if $x is equal to $y |
=== | Identical | $x === $y | Returns true if $x is equal to $y, and they are of the same type |
!= | Not equal | $x != $y | Returns true if $x is not equal to $y |
<> | Not equal | $x <> $y | Returns true if $x is not equal to $y |
!== | Not identical | $x !== $y | Returns true if $x is not equal to $y, or they are not of the same type |
> | Greater than | $x > $y | Returns true if $x is greater than $y |
< | Less than | $x < $y | Returns true if $x is less than $y |
>= | Greater than or equal to | $x >= $y | Returns true if $x is greater than or equal to $y |
<= | Less than or equal to | $x <= $y | Returns true if $x is less than or equal to $y |
<=> | Spaceship | $x <=> $y | Returns an integer less than, equal to, or greater than zero, depending on if $x is less than, equal to, or greater than $y. Introduced in PHP 7. |
Operator | Name | Description |
---|---|---|
++$x | Pre-increment | Increments $x by one, then returns $x |
$x++ | Post-increment | Returns $x, then increments $x by one |
--$x | Pre-decrement | Decrements $x by one, then returns $x |
$x-- | Post-decrement | Returns $x, then decrements $x by one |
Operator | Name | Example | Result |
---|---|---|---|
and | And | $x and $y | True if both $x and $y are true |
or | Or | $x or $y | True if either $x or $y is true |
xor | Xor | $x xor $y | True if either $x or $y is true, but not both |
&& | And | $x && $y | True if both $x and $y are true |
|| | Or | $x || $y | True if either $x or $y is true |
! | Not | !$x | True if $x is not true |
Operator | Name | Example | Result |
---|---|---|---|
. | Concatenation | $txt1 . $txt2 | Concatenation of $txt1 and $txt2 |
.= | Concatenation assignment | $txt1 .= $txt2 | Appends $txt2 to $txt1 |
Operator | Name | Example | Result |
---|---|---|---|
+ | Union | $x + $y | Union of $x and $y |
== | Equality | $x == $y | Returns true if $x and $y have the same key/value pairs |
=== | Identity | $x === $y | Returns true if $x and $y have the same key/value pairs in the same order and of the same types |
!= | Inequality | $x != $y | Returns true if $x is not equal to $y |
<> | Inequality | $x <> $y | Returns true if $x is not equal to $y |
!== | Non-identity | $x !== $y | Returns true if $x is not identical to $y |
Operator | Name | Example | Result |
---|---|---|---|
?: | Ternary | $x = expr1 ? expr2 : expr3 | Returns the value of $x. The value of $x is expr2 if expr1 = TRUE. The value of $x is expr3 if expr1 = FALSE |
?? | Null coalescing | $x = expr1 ?? expr2 | Returns the value of $x. The value of $x is expr1 if expr1 exists, and is not NULL. If expr1 does not exist, or is NULL, the value of $x is expr2. Introduced in PHP 7 |
if (condition) {
code to be executed if condition is true;
}
if (condition) {
code to be executed if condition is true;
} else {
code to be executed if condition is false;
}
if (condition) {
code to be executed if this condition is true;
} elseif (condition) {
code to be executed if first condition is false and this condition is true;
} else {
code to be executed if all conditions are false;
}
switch (n) {
case label1:
code to be executed if n=label1;
break;
case label2:
code to be executed if n=label2;
break;
case label3:
code to be executed if n=label3;
break;
...
default:
code to be executed if n is different from all labels;
}
while (condition is true) {
code to be executed;
}
do {
code to be executed;
} while (condition is true);
for (init counter; test counter; increment counter) {
code to be executed for each iteration;
}
foreach ($array as $value) {
code to be executed;
}
for ($x = 0; $x < 10; $x++) {
if ($x == 4) {
break;
}
echo "The number is: $x
";
}
for ($x = 0; $x < 10; $x++) {
if ($x == 4) {
continue;
}
echo "The number is: $x
";
}
function functionName() {
code to be executed;
}
Function | Description |
---|---|
array() | Creates an array |
array_change_key_case() | Changes all keys in an array to lowercase or uppercase |
array_chunk() | Splits an array into chunks of arrays |
array_column() | Returns the values from a single column in the input array |
array_combine() | Creates an array by using the elements from one "keys" array and one "values" array |
array_count_values() | Counts all the values of an array |
array_diff() | Compare arrays, and returns the differences (compare values only) |
array_diff_assoc() | Compare arrays, and returns the differences (compare keys and values) |
array_diff_key() | Compare arrays, and returns the differences (compare keys only) |
array_diff_uassoc() | Compare arrays, and returns the differences (compare keys and values, using a user-defined key comparison function) |
array_diff_ukey() | Compare arrays, and returns the differences (compare keys only, using a user-defined key comparison function) |
array_fill() | Fills an array with values |
array_fill_keys() | Fills an array with values, specifying keys |
array_filter() | Filters the values of an array using a callback function |
array_flip() | Flips/Exchanges all keys with their associated values in an array |
array_intersect() | Compare arrays, and returns the matches (compare values only) |
array_intersect_assoc() | Compare arrays and returns the matches (compare keys and values) |
array_intersect_key() | Compare arrays, and returns the matches (compare keys only) |
array_intersect_uassoc() | Compare arrays, and returns the matches (compare keys and values, using a user-defined key comparison function) |
array_intersect_ukey() | Compare arrays, and returns the matches (compare keys only, using a user-defined key comparison function) |
array_key_exists() | Checks if the specified key exists in the array |
array_keys() | Returns all the keys of an array |
array_map() | Sends each value of an array to a user-made function, which returns new values |
array_merge() | Merges one or more arrays into one array |
array_merge_recursive() | Merges one or more arrays into one array recursively |
array_multisort() | Sorts multiple or multi-dimensional arrays |
array_pad() | Inserts a specified number of items, with a specified value, to an array |
array_pop() | Deletes the last element of an array |
array_product() | Calculates the product of the values in an array |
array_push() | Inserts one or more elements to the end of an array |
array_rand() | Returns one or more random keys from an array |
array_reduce() | Returns an array as a string, using a user-defined function |
array_replace() | Replaces the values of the first array with the values from following arrays |
array_replace_recursive() | Replaces the values of the first array with the values from following arrays recursively |
array_reverse() | Returns an array in the reverse order |
array_search() | Searches an array for a given value and returns the key |
array_shift() | Removes the first element from an array, and returns the value of the removed element |
array_slice() | Returns selected parts of an array |
array_splice() | Removes and replaces specified elements of an array |
array_sum() | Returns the sum of the values in an array |
array_udiff() | Compare arrays, and returns the differences (compare values only, using a user-defined key comparison function) |
array_udiff_assoc() | Compare arrays, and returns the differences (compare keys and values, using a built-in function to compare the keys and a user-defined function to compare the values) |
array_udiff_uassoc() | Compare arrays, and returns the differences (compare keys and values, using two user-defined key comparison functions) |
array_uintersect() | Compare arrays, and returns the matches (compare values only, using a user-defined key comparison function) |
array_uintersect_assoc() | Compare arrays, and returns the matches (compare keys and values, using a built-in function to compare the keys and a user-defined function to compare the values) |
array_uintersect_uassoc() | Compare arrays, and returns the matches (compare keys and values, using two user-defined key comparison functions) |
array_unique() | Removes duplicate values from an array |
array_unshift() | Adds one or more elements to the beginning of an array |
array_values() | Returns all the values of an array |
array_walk() | Applies a user function to every member of an array |
array_walk_recursive() | Applies a user function recursively to every member of an array |
arsort() | Sorts an associative array in descending order, according to the value |
asort() | Sorts an associative array in ascending order, according to the value |
compact() | Create array containing variables and their values |
count() | Returns the number of elements in an array |
current() | Returns the current element in an array |
each() | Deprecated from PHP 7.2. Returns the current key and value pair from an array |
end() | Sets the internal pointer of an array to its last element |
extract() | Imports variables into the current symbol table from an array |
in_array() | Checks if a specified value exists in an array |
key() | Fetches a key from an array |
krsort() | Sorts an associative array in descending order, according to the key |
ksort() | Sorts an associative array in ascending order, according to the key |
list() | Assigns variables as if they were an array |
natcasesort() | Sorts an array using a case insensitive "natural order" algorithm |
natsort() | Sorts an array using a "natural order" algorithm |
next() | Advance the internal array pointer of an array |
pos() | Alias of current() |
prev() | Rewinds the internal array pointer |
range() | Creates an array containing a range of elements |
reset() | Sets the internal pointer of an array to its first element |
rsort() | Sorts an indexed array in descending order |
shuffle() | Shuffles an array |
sizeof() | Alias of count() |
sort() | Sorts an indexed array in ascending order |
uasort() | Sorts an array by values using a user-defined comparison function |
uksort() | Sorts an array by keys using a user-defined comparison function |
usort() | Sorts an array using a user-defined comparison function |
$cars = array("Volvo", "BMW", "Toyota");
$age = array("Peter"=>"35", "Ben"=>"37", "Joe"=>"43");
echo $cars[0][0]
$cars = array("Volvo", "BMW", "Toyota");
sort($cars);
$cars = array("Volvo", "BMW", "Toyota");
rsort($cars);
$age = array("Peter"=>"35", "Ben"=>"37", "Joe"=>"43");
asort($age);
$age = array("Peter"=>"35", "Ben"=>"37", "Joe"=>"43");
ksort($age);
$age = array("Peter"=>"35", "Ben"=>"37", "Joe"=>"43");
arsort($age);
$age = array("Peter"=>"35", "Ben"=>"37", "Joe"=>"43");
krsort($age);
Function | Description |
---|---|
preg_match() | Returns 1 if the pattern was found in the string and 0 if not |
preg_match_all() | Returns the number of times the pattern was found in the string, which may also be 0 |
preg_replace() | Returns a new string where matched patterns have been replaced with another string |
$str = "Visit W3Schools";
$pattern = "/w3schools/i";
echo preg_match($pattern, $str); // Outputs 1
$str = "The rain in SPAIN falls mainly on the plains.";
$pattern = "/ain/i";
echo preg_match_all($pattern, $str); // Outputs 4
$str = "Visit Microsoft!";
$pattern = "/microsoft/i";
echo preg_replace($pattern, "W3Schools", $str); // Outputs "Visit W3Schools!"
Modifier | Description |
---|---|
i | Performs a case-insensitive search |
m | Performs a multiline search (patterns that search for the beginning or end of a string will match the beginning or end of each line) |
u | Enables correct matching of UTF-8 encoded patterns |
Expression | Description |
---|---|
[abc] | Find one character from the options between the brackets |
[^abc] | Find any character NOT between the brackets |
[0-9] | Find one character from the range 0 to 9 |
Metacharacter | Description |
---|---|
| | Find a match for any one of the patterns separated by | as in: cat|dog|fish |
. | Find just one instance of any character |
^ | Finds a match as the beginning of a string as in: ^Hello |
$ | Finds a match at the end of the string as in: World$ |
\d | Find a digit |
\s | Find a whitespace character |
\b | Find a match at the beginning of a word like this: \bWORD, or at the end of a word like this: WORD\b |
\uxxxx | Find the Unicode character specified by the hexadecimal number xxxx |
Quantifier | Description |
---|---|
n+ | Matches any string that contains at least one n |
n* | Matches any string that contains zero or more occurrences of n |
n? | Matches any string that contains zero or one occurrences of n |
n{x} | Matches any string that contains a sequence of X n's |
n{x,y} | Matches any string that contains a sequence of X to Y n's |
n{x,} | Matches any string that contains a sequence of at least X n's |
<html>
<body><form action="welcome.php" method="post">
Name: <input type="text" name="name"><br>
E-mail: <input type="text" name="email"><br>
<input type="submit">
</form></body>
</html>
Field | Validation Rules |
---|---|
Name | Required. + Must only contain letters and whitespace |
Required. + Must contain a valid email address (with @ and .) | |
Website | Optional. If present, it must contain a valid URL |
Comment | Optional. Multi-line input field (textarea) |
Gender | Required. Must select one |
<!DOCTYPE HTML>
<html>
<head>
<style>
.error {color: #FF0000;}
</style>
</head>
<body>
<?php
// define variables and set to empty values
$nameErr = $emailErr = $genderErr = $websiteErr = "";
$name = $email = $gender = $comment = $website = "";
if ($_SERVER["REQUEST_METHOD"] == "POST") {
if (empty($_POST["name"])) {
$nameErr = "Name is required";
} else {
$name = test_input($_POST["name"]);
// check if name only contains letters and whitespace
if (!preg_match("/^[a-zA-Z-' ]*$/",$name)) {
$nameErr = "Only letters and white space allowed";
}
}
if (empty($_POST["email"])) {
$emailErr = "Email is required";
} else {
$email = test_input($_POST["email"]);
// check if e-mail address is well-formed
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
$emailErr = "Invalid email format";
}
}
if (empty($_POST["website"])) {
$website = "";
} else {
$website = test_input($_POST["website"]);
// check if URL address syntax is valid (this regular expression also allows dashes in the URL)
if (!preg_match("/\b(?:(?:https?|ftp):\/\/|www\.)[-a-z0-9+&@#\/%?=~_|!:,.;]*[-a-z0-9+&@#\/%=~_|]/i",$website)) {
$websiteErr = "Invalid URL";
}
}
if (empty($_POST["comment"])) {
$comment = "";
} else {
$comment = test_input($_POST["comment"]);
}
if (empty($_POST["gender"])) {
$genderErr = "Gender is required";
} else {
$gender = test_input($_POST["gender"]);
}
}
function test_input($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
?>
<h2>PHP Form Validation Example</h2>
<p><span class="error">* required field</span></p>
<form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">
Name: <input type="text" name="name" value="<?php echo $name;?>">
<span class="error">* <?php echo $nameErr;?></span>
<br><br>
E-mail: <input type="text" name="email" value="<?php echo $email;?>">
<span class="error">* <?php echo $emailErr;?></span>
<br><br>
Website: <input type="text" name="website" value="<?php echo $website;?>">
<span class="error"><?php echo $websiteErr;?></span>
<br><br>
Comment: <textarea name="comment" rows="5" cols="40"><?php echo $comment;?></textarea>
<br><br>
Gender:
<input type="radio" name="gender" <?php if (isset($gender) && $gender=="female") echo "checked";?> value="female">Female
<input type="radio" name="gender" <?php if (isset($gender) && $gender=="male") echo "checked";?> value="male">Male
<input type="radio" name="gender" <?php if (isset($gender) && $gender=="other") echo "checked";?> value="other">Other
<span class="error">* <?php echo $genderErr;?></span>
<br><br>
<input type="submit" name="submit" value="Submit">
</form>
<?php
echo "<h2>Your Input:</h2>";
echo $name;
echo "<br>";
echo $email;
echo "<br>";
echo $website;
echo "<br>";
echo $comment;
echo "<br>";
echo $gender;
?>
</body>
</html>