Skip to content

Instantly share code, notes, and snippets.

@p3t3r67x0
Last active January 31, 2019 18:04
Show Gist options
  • Save p3t3r67x0/73f8c05f2964aae2599a0493d30b9c48 to your computer and use it in GitHub Desktop.
Save p3t3r67x0/73f8c05f2964aae2599a0493d30b9c48 to your computer and use it in GitHub Desktop.

Variables

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;

Datatypes

In php we have several datatypes like boolean, string, integer and float. However we php does not strictly cotrol these types.

String

Strings are always between two double quots.

$string = "Hello World";

Boolean

A boolean expression is a value that is either true or false.

$boolean = true;

Integer

An integer is a number without a decimal point, the value can be positive or negative.

$integer = 123;

Float

A float is a floating-point number, which means it is a number that has a decimal place.

$float = 0.29;

Arithmetic operators

An arithmetic operator is a mathematical function that takes two operands and performs a calculation on them.

$number1 = 23;
$number2 = 5;

Addition

Addition is finding the total, or sum, by combining two or more numbers.

$result = $number1 + $number2;
echo $result;
// 28

Subtraction

Taking one number away from another.

$result = $number1 - $number2;
echo $result;
// 18

Division

Division is splitting into equal parts or groups.

$result = $number1 / $number2;
echo $result;
// 4.6

Multiplication

The basic idea of multiplication is repeated addition.

$result = $number1 * $number2;
echo $result;
// 115

Modulo

The operation or function that returns the remainder of one number divided by another.

$result = $number1 % $number2;
echo $result;
// 3

Logical operators

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;

And

Performs a logical and of the two operands.

$result = $op1 && $op2;
echo $result;
// false

Or

Performs a logical or of the two operands.

$result = $op1 || $op2;
echo $result;
// true

Not

Performs a logical not of the operand.

$result = !$op1;
echo $result;
// false

Conditions

Conditional statements are used to perform different actions based on different conditions.

$condition = true;

The if statement

if ($condition == true) {
  // block of code to be executed if the condition is true
}

The else statement

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
}

The else if statement

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
}

Arrays

An array stores multiple values in one single variable. An array is a special variable, which can hold more than one value.

Types of arrays

  • Indexed arrays - Arrays with a numeric index
  • Associative arrays - Arrays with named keys
  • Multidimensional arrays - Arrays containing one or more arrays

Indexed array

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

Get the length of an array

The count() function is used to return the length of an array.

echo count($cars);

// 3

Loop through an indexed array

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

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 functions for arrays

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 )

Loop through an associative array

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

Multidimensional Arrays

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

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

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

Strings

String functions are part of the PHP core. No installation is required to use these functions.

addcslashes()

Returns a string with backslashes in front of the specified characters

$str = addcslashes("Hello World!", "W");
echo($str);

//  Hello \World! 

addslashes()

Returns a string with backslashes in front of predefined characters.

$str = addslashes('Hello "World"!');
echo($str);

// Hello \"World\"!

bin2hex()

Converts a string of ASCII characters to hexadecimal values.

$str = bin2hex("Hello World!");
echo $str;

// 48656c6c6f20576f726c6421

chop()

Removes whitespace or other characters from the right end of a string.

$str = "Hello World!";
echo chop($str, "World!");

// Hello

chunk_split()

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.!.

crc32()

Calculates a 32-bit CRC for a string.

$str = crc32("Hello World!");
echo $str;

// 472456355

explode()

Breaks a string into an array.

$str = "Hello world!";
print_r(explode(" ", $str));

// Array ( [0] => Hello [1] => world! ) 

htmlentities()

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>

htmlspecialchars()

Converts some predefined characters to HTML entities.

$str = "Hello <strong>World</strong>!";
echo htmlspecialchars($str);

// Hello &lt;strong&gt;World&lt;/strong&gt;!

implode()

Returns a string from the elements of an array.

$arr = array("Hello", "World!");
echo implode(" ", $arr);

// Hello World!

lcfirst()

Converts the first character of a string to lowercase.

$str = lcfirst("Hello world!");
echo $str;

// hello world!

ltrim()

Removes whitespace or other characters from the left side of a string.

$str = "Hello World!";
echo ltrim($str, "Hello");

// World!

md5()

Calculates the MD5 hash of a string.

$str = "Hello World!";
echo md5($str);

// ed076287532e86365e841e92bfc50d8c

money_format()

Returns a string formatted as a currency string.

$number = 1234.56;
setlocale(LC_MONETARY, "de_DE");
echo money_format("%.2n", $number);

// 1234,56 EUR

nl2br()

Inserts HTML line breaks in front of each newline in a string.

echo nl2br("Hello\nWorld!");

// Hello
// World!

rtrim()

Removes whitespace or other characters from the right side of a string.

$str = "Hello World!";
echo rtrim($str, "World!");

// Hello

sha1()

Calculates the SHA-1 hash of a string.

$str = "Hello World!";
echo sha1($str);

2ef7bde608ce5404e97d5f042f95f89f1c232871

str_ireplace()

Replaces some characters in a string (case-insensitive).

$str = "Hello World!";
echo str_ireplace("WORLD","Moon", $str);

// Hello Moon!

str_pad()

Pads a string to a new length.

$str = "Hello World!";
echo str_pad($str, 20, ".");

// Hello World!........

str_repeat()

Repeats a string a specified number of times.

echo str_repeat(".", 20);

// ....................

str_replace()

Replaces some characters in a string (case-sensitive).

$str = "Hello World!";
echo str_replace("World", "Moon", $str);

// Hello Moon!

str_shuffle()

Randomly shuffles all characters in a string.

$str = "Hello World!";
echo str_shuffle($str);

// ldl!oolreW H

str_split()

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] => ! ) 

str_word_count()

Count the number of words in a string.

$str = "Hello World!";
echo str_word_count($str);

// 2

strip_tags()

Strips HTML and PHP tags from a string.

$str = "Hello <strong>World</strong>!";
echo strip_tags($str);

// Hello World!

strlen()

Returns the length of a string.

$str = "Hello World!";
echo strlen($str);

// 12

strpos()

Returns the position of the first occurrence of a string inside another string (case-sensitive).

$str = "Hello World!";
echo stripos($str, "World");

// 6

strrchr()

Finds the last occurrence of a string inside another string.

$str = "Hello World!";
echo strrchr($str, "World");

// World!

strrev()

Reverses a string.

$str = "Hello World!";
echo strrev($str);

// !dlroW olleH

strripos()

Finds the position of the last occurrence of a string inside another string (case-insensitive)

$str = "Hello World!";
echo strripos($str, "WORLD");

// 6

strrpos()

Finds the position of the last occurrence of a string inside another string (case-sensitive).

$str = "Hello World!";
echo strrpos($str, "World"); 

// 6

strstr()

Finds the first occurrence of a string inside another string (case-sensitive).

$str = "Hello World!";
echo strstr($str, "World");

// World!

strtok()

Splits a string into smaller strings.

$str = "Hello World!";
echo strtok($str, " ");

// Hello

strtolower()

Converts a string to lowercase letters.

$str = "Hello World!";
echo strtolower($str);

// hello world!

strtoupper()

Converts a string to uppercase letters.

$str = "Hello World!";
echo strtoupper($str);

// HELLO WORLD!

substr()

Returns a part of a string.

$str = "Hello World!";
echo substr($str, 6);

// World!

substr_count()

Counts the number of times a substring occurs in a string.

$str = "Hello World!";
echo substr_count($str, "World");

// 1

substr_replace()

Replaces a part of a string with another string.

$str = "Hello World!";
echo substr_replace($str, "WORLD", -2);

// Hello WorlWORLD

trim()

Removes whitespace or other characters from both sides of a string.

$str = "Hello World!";
echo trim($str, "Hed!");

// llo Worl

ucfirst()

Converts the first character of a string to uppercase

$str = "hello world!";
echo ucfirst($str);

// Hello world!

ucwords()

Converts the first character of each word in a string to uppercase.

$str = "hello world!";
echo ucwords($str);

// Hello World!

wordwrap()

Wraps a string to a given number of characters.

$str = "Hello World!";
echo wordwrap($str, 7, "<br>");

// Hello
// World!
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment