You need variables to store some data. Variables always starts with a $
sign followed by lower- or uppercase letters or an underscore. You should allocate some data to variables so you can access this data later when calling a variable.
$string = "Hello World!";
$boolean = true;
$integer = 123;
$float = 0.29;
To acceess the data from you variable you must call the variable name starting with dollar sign, see the following example.
echo $string;
In php we have several datatypes like boolean
, string
, integer
and float
. However we php does not strictly cotrol these types.
Strings are always between two double quots.
$string = "Hello World";
A boolean expression is a value that is either true
or false
.
$boolean = true;
An integer is a number without a decimal point, the value can be positive or negative.
$integer = 123;
A float is a floating-point number, which means it is a number that has a decimal place.
$float = 0.29;
An arithmetic operator is a mathematical function that takes two operands and performs a calculation on them.
$number1 = 23;
$number2 = 5;
Addition is finding the total, or sum, by combining two or more numbers.
$result = $number1 + $number2;
echo $result;
// 28
Taking one number away from another.
$result = $number1 - $number2;
echo $result;
// 18
Division is splitting into equal parts or groups.
$result = $number1 / $number2;
echo $result;
// 4.6
The basic idea of multiplication is repeated addition.
$result = $number1 * $number2;
echo $result;
// 115
The operation or function that returns the remainder of one number divided by another.
$result = $number1 % $number2;
echo $result;
// 3
Logical operators are mainly used to control program flow. Usually, you will find them as part of an if
, a while
, or some other control statement.
$op1 = true;
$op2 = false;
Performs a logical and
of the two operands.
$result = $op1 && $op2;
echo $result;
// false
Performs a logical or
of the two operands.
$result = $op1 || $op2;
echo $result;
// true
Performs a logical not
of the operand.
$result = !$op1;
echo $result;
// false
Conditional statements are used to perform different actions based on different conditions.
$condition = true;
if ($condition == true) {
// block of code to be executed if the condition is true
}
Use the else statement to specify a block of code to be executed if the condition is false.
if ($condition != true) {
// block of code to be executed if the condition is true
} else {
// block of code to be executed if the condition is false
}
Use the else if statement to specify a new condition if the first condition is false.
if (!$condition) {
// block of code to be executed if condition1 is true
} else if ($condition) {
// block of code to be executed if the condition1 is false and condition2 is true
} else {
// block of code to be executed if the condition1 is false and condition2 is false
}
An array stores multiple values in one single variable. An array is a special variable, which can hold more than one value.
- Indexed arrays - Arrays with a numeric index
- Associative arrays - Arrays with named keys
- Multidimensional arrays - Arrays containing one or more arrays
The index can be assigned automatically. Remember that the index always starts at 0
.
$cars = array("Volvo", "BMW", "Toyota");
echo $cars[0];
// Volvo
echo $cars[1];
// BMW
echo $cars[2];
// Toyota
The count()
function is used to return the length of an array.
echo count($cars);
// 3
To loop through and print all the values of an indexed array, you could use a for
loop.
for($i = 0; $i < count($cars); $i++) {
echo $cars[$i];
}
// VolvoBMWToyota
Associative arrays are arrays that use named keys that you assign to them.
$age = array("Peter" => "35", "Ben" => "37", "Joe" => "43");
echo $age['Peter'];
// 35
Sort arrays in ascending order.
$numbers = array(4, 6, 2, 22, 11);
sort($numbers);
print_r($numbers);
// Array ( [0] => 2 [1] => 4 [2] => 6 [3] => 11 [4] => 22 )
Sort arrays in descending order.
$numbers = array(4, 6, 2, 22, 11);
rsort($numbers);
print_r($numbers);
// Array ( [0] => 22 [1] => 11 [2] => 6 [3] => 4 [4] => 2 )
Sort associative arrays in ascending order, according to the value.
$age = array("Peter" => "35", "Ben" => "37", "Joe" => "43");
asort($age);
print_r($age);
// Array ( [Peter] => 35 [Ben] => 37 [Joe] => 43 )
Sort associative arrays in ascending order, according to the key.
$age = array("Peter" => "35", "Ben" => "37", "Joe" => "43");
ksort($age);
print_r($age);
// Array ( [Ben] => 37 [Joe] => 43 [Peter] => 35 )
Sort associative arrays in descending order, according to the value.
$age = array("Peter" => "35", "Ben" => "37", "Joe" => "43");
arsort($age);
print_r($age);
// Array ( [Joe] => 43 [Ben] => 37 [Peter] => 35 )
Sort associative arrays in descending order, according to the key.
$age = array("Peter" => "35", "Ben" => "37", "Joe" => "43");
krsort($age);
print_r($age);
// Array ( [Peter] => 35 [Joe] => 43 [Ben] => 37 )
To loop through and print the values of an associative array, you could use a foreach
loop.
$age = array("Peter" => "35", "Ben" => "37", "Joe" => "43");
foreach($age as $key => $value) {
echo $key . ", " . $value . "<br>";
}
// Peter, 35
// Ben, 37
// Joe, 43
A multidimensional array is an array containing one or more arrays.
$cars = array(
array("Volvo", 22, 18),
array("BMW", 15, 13),
array("Saab", 5, 2)
);
echo $cars[0][0] . ", " . $cars[0][1] . ", " . $cars[0][2];
// Volvo, 22, 18
The for loop is used when you know in advance how many times the script should run.
for ($i = 0; $i < 3; $i++) {
echo $i . "<br>";
}
// 0
// 1
// 2
The foreach loop works only on arrays, and is used to loop through each key value pair in an array.
$array = array("house", "tree", "car");
foreach ($array as $value) {
echo $value . "<br>";
}
// house
// tree
// car
String functions are part of the PHP core. No installation is required to use these functions.
Returns a string with backslashes in front of the specified characters
$str = addcslashes("Hello World!", "W");
echo($str);
// Hello \World!
Returns a string with backslashes in front of predefined characters.
$str = addslashes('Hello "World"!');
echo($str);
// Hello \"World\"!
Converts a string of ASCII characters to hexadecimal values.
$str = bin2hex("Hello World!");
echo $str;
// 48656c6c6f20576f726c6421
Removes whitespace or other characters from the right end of a string.
$str = "Hello World!";
echo chop($str, "World!");
// Hello
Splits a string into a series of smaller parts.
$str = "Hello world!";
echo chunk_split($str, 1, ".");
// H.e.l.l.o. .w.o.r.l.d.!.
Calculates a 32-bit CRC for a string.
$str = crc32("Hello World!");
echo $str;
// 472456355
Breaks a string into an array.
$str = "Hello world!";
print_r(explode(" ", $str));
// Array ( [0] => Hello [1] => world! )
Converts characters to HTML entities.
$str = '<a href="https://www.wikipedia.org">www.wikipedia.org</a>';
echo htmlentities($str);
// <a href="https://www.wikipedia.org">www.wikipedia.org</a>
Converts some predefined characters to HTML entities.
$str = "Hello <strong>World</strong>!";
echo htmlspecialchars($str);
// Hello <strong>World</strong>!
Returns a string from the elements of an array.
$arr = array("Hello", "World!");
echo implode(" ", $arr);
// Hello World!
Converts the first character of a string to lowercase.
$str = lcfirst("Hello world!");
echo $str;
// hello world!
Removes whitespace or other characters from the left side of a string.
$str = "Hello World!";
echo ltrim($str, "Hello");
// World!
Calculates the MD5 hash of a string.
$str = "Hello World!";
echo md5($str);
// ed076287532e86365e841e92bfc50d8c
Returns a string formatted as a currency string.
$number = 1234.56;
setlocale(LC_MONETARY, "de_DE");
echo money_format("%.2n", $number);
// 1234,56 EUR
Inserts HTML line breaks in front of each newline in a string.
echo nl2br("Hello\nWorld!");
// Hello
// World!
Removes whitespace or other characters from the right side of a string.
$str = "Hello World!";
echo rtrim($str, "World!");
// Hello
Calculates the SHA-1 hash of a string.
$str = "Hello World!";
echo sha1($str);
2ef7bde608ce5404e97d5f042f95f89f1c232871
Replaces some characters in a string (case-insensitive).
$str = "Hello World!";
echo str_ireplace("WORLD","Moon", $str);
// Hello Moon!
Pads a string to a new length.
$str = "Hello World!";
echo str_pad($str, 20, ".");
// Hello World!........
Repeats a string a specified number of times.
echo str_repeat(".", 20);
// ....................
Replaces some characters in a string (case-sensitive).
$str = "Hello World!";
echo str_replace("World", "Moon", $str);
// Hello Moon!
Randomly shuffles all characters in a string.
$str = "Hello World!";
echo str_shuffle($str);
// ldl!oolreW H
Splits a string into an array.
$str = "Hello World!";
print_r(str_split($str));
// Array ( [0] => H [1] => e [2] => l [3] => l [4] => o [5] => [6] => W [7] => o [8] => r [9] => l [10] => d [11] => ! )
Count the number of words in a string.
$str = "Hello World!";
echo str_word_count($str);
// 2
Strips HTML and PHP tags from a string.
$str = "Hello <strong>World</strong>!";
echo strip_tags($str);
// Hello World!
Returns the length of a string.
$str = "Hello World!";
echo strlen($str);
// 12
Returns the position of the first occurrence of a string inside another string (case-sensitive).
$str = "Hello World!";
echo stripos($str, "World");
// 6
Finds the last occurrence of a string inside another string.
$str = "Hello World!";
echo strrchr($str, "World");
// World!
Reverses a string.
$str = "Hello World!";
echo strrev($str);
// !dlroW olleH
Finds the position of the last occurrence of a string inside another string (case-insensitive)
$str = "Hello World!";
echo strripos($str, "WORLD");
// 6
Finds the position of the last occurrence of a string inside another string (case-sensitive).
$str = "Hello World!";
echo strrpos($str, "World");
// 6
Finds the first occurrence of a string inside another string (case-sensitive).
$str = "Hello World!";
echo strstr($str, "World");
// World!
Splits a string into smaller strings.
$str = "Hello World!";
echo strtok($str, " ");
// Hello
Converts a string to lowercase letters.
$str = "Hello World!";
echo strtolower($str);
// hello world!
Converts a string to uppercase letters.
$str = "Hello World!";
echo strtoupper($str);
// HELLO WORLD!
Returns a part of a string.
$str = "Hello World!";
echo substr($str, 6);
// World!
Counts the number of times a substring occurs in a string.
$str = "Hello World!";
echo substr_count($str, "World");
// 1
Replaces a part of a string with another string.
$str = "Hello World!";
echo substr_replace($str, "WORLD", -2);
// Hello WorlWORLD
Removes whitespace or other characters from both sides of a string.
$str = "Hello World!";
echo trim($str, "Hed!");
// llo Worl
Converts the first character of a string to uppercase
$str = "hello world!";
echo ucfirst($str);
// Hello world!
Converts the first character of each word in a string to uppercase.
$str = "hello world!";
echo ucwords($str);
// Hello World!
Wraps a string to a given number of characters.
$str = "Hello World!";
echo wordwrap($str, 7, "<br>");
// Hello
// World!