PHP String Functions

  • A string is a sequence of characters, like "Hello world!".
    Function Description Example
    strlen() The PHP strlen() function returns the length of a string.
                                  
    echo strlen("Hello world!"); 
    // outputs 12
                                  
                                
    str_word_count() The PHP str_word_count() function counts the number of words in a string.
                                  
    echo str_word_count("Hello world!"); 
    // outputs 2
                                  
                                
    strrev() The PHP strrev() function reverses a string.
                                  
    echo strrev("Hello world!"); 
    // outputs !dlrow olleH
                                  
                                
    strpos() The PHP strpos() function searches for a specific text within a string. If a match is found, the function returns the character position of the first match. If no match is found, it will return FALSE.
                                  
    echo strpos("Hello world!", "world"); 
    // outputs 6
                                  
                                
    strrpos() Finds the position of the last occurrence of a string inside another string(case-sensitive)
                                  
    $x = 'hello world world';
    $z = strpos($x,"wor");
    var_dump($z);
    // int(12)
                                
                              
    str_replace() The PHP str_replace() function replaces some characters with some other characters in a string.
                                  
    echo str_replace("world", "Dolly", "Hello world!");
    // outputs Hello Dolly!
                                
                              
    chunk_split() Split a string into a series of smaller parts.
                                  
    echo chunk_split("Hello world", 3, "@");
    // outputs Hel@lo @wor@ld@
                                
                              
    str_split() Splits a string into an array.
                                  
    var_dump(str_split("Hello world", 3));
    // array(4) { [0]=> string(3) "Hel" 
    [1]=> string(3) "lo "
    [2]=> string(3) "wor" [3]=> string(2) "ld" }
                                
                              
    str_shuffle() Randomly shuffles all characters in a string.
                                  
    var_dump(str_shuffle("Hello world"));
    //string(11) "r edHllwloo"
                                
                              
    explode() Breaks a string into an array.
                                  
    $x = 'hello world';
    $y = explode(' ',$x);
    var_dump($y);
    // array(2) { [0]=> string(5)
    "hello" [1]=> string(5) "world" }
                                
                              
    implode() = join() Returns a string from the elements of an array.
                                  
    $x = 'hello world';
    $y = explode(' ',$x);
    $z = implode('@',$y);
    var_dump($z);
    // string(11) "hello@world"
                                
                              
    htmlspecialchars() Converts some predefined characters to HTML entities
                                  
    $x = '<h1>hello world</h1>';
    $z = htmlspecialchars($x);
    echo($z);
    // <h1>hello world</h1>
                                
                              
    htmlspecialchars_decode() Converts some predefined HTML entities to characters.
                                  
    $x = '<h1>hello world</h1>';
    $z = htmlspecialchars_decode($x);
    echo($z);
    // output : 

    hello world

    md5() Calculates the md5 hash of a string.
                                  
    $x = 'hello world';
    $z = md5($x);
    var_dump($z);
    // string(32) 
    "5eb63bbbe01eeed093cb22bb8f5acdc3"
                                
                              
    sha1() Calculates the SHA-1 hash of a string.
                                  
    $x = 'hello world';
    $z = sha1($x);
    var_dump($z);
    // string(40) 
    "2aae6c35c94fcfb415dbe95f408b9ce91ee846ed"
                                
                              
    trim() Strips whitespace from both sides of a string.
                                  
    $x = ' hello world ';
    $z = trim($x);
    var_dump($z);
    // string(40) "hello world"
                                
                              
    strtolower() Converts a string to lowercase letters
                                  
    $x = 'HELLO WORLD';
    $z = strtolower($x);
    var_dump($z);
    // string(40) "hello world"
                                
                              
    strtoupper() Converts a string to uppercase letters.
                                  
    $x = 'hello world';
    $z = strtoupper($x);
    var_dump($z);
    // string(40) "HELLO WORLD"
                                
                              

PHP Arrays

  • An array stores multiple values in one single variable
  • In PHP, the array() function is used to create an array
  • The count() function is used to return the length (the number of elements) of an array
  • Example:
                  
        $cars = array("Volvo", "BMW", "Toyota");
        echo "I like " . $cars[0] . ", " . $cars[1] . " and " . $cars[2] . ".";
                  
                
                  
        $cars = array("Volvo", "BMW", "Toyota");
        echo count($cars);
                  
                

PHP Indexed Array

  • There are two ways to create indexed arrays :
    Example :
                  
      1-
      $cars = array("Volvo", "BMW", "Toyota");
                  
                  
      2-
      $cars[0] = "Volvo";
      $cars[1] = "BMW";
      $cars[2] = "Toyota";
                  
                
    get access :
                  
      $cars = array("Volvo", "BMW", "Toyota");
      echo "I like " . $cars[0] . ", " . $cars[1] . " and " . $cars[2] . ".";
                  
                

PHP Associative Array

  • There are two ways to create associative arrays :
    Example :
                  
      1-
      $age = array("Peter"=>"35", "Ben"=>"37", "Joe"=>"43");
                  
                  
      2-
      $age['Peter'] = "35";
      $age['Ben'] = "37";
      $age['Joe'] = "43";
                  
                
    get access :
                  
      $age = array("Peter"=>"35", "Ben"=>"37", "Joe"=>"43");
      echo "Peter is " . $age['Peter'] . " years old.";
                  
                

PHP Multidimensional Array

  • A two-dimensional array is an array of arrays (a three-dimensional array is an array of arrays of arrays).
    Example :
                  
      $cars = array (
      array("Volvo",22,18),
      array("BMW",15,13),
      array("Saab",5,2),
      array("Land Rover",17,15)
      );
                  
                
    get access :
    echo $cars[0][0].": In stock: ".$cars[0][1].", sold: ".$cars[0][2].".<br>"; echo $cars[1][0].": In stock: ".$cars[1][1].", sold: ".$cars[1][2].".<br>"; echo $cars[2][0].": In stock: ".$cars[2][1].", sold: ".$cars[2][2].".<br>"; echo $cars[3][0].": In stock: ".$cars[3][1].", sold: ".$cars[3][2].".<br>";

PHP Sorting Arrays

  • The elements in an array can be sorted in alphabetical or numerical order, descending or ascending.
    Function Description Example
    sort() sort arrays in ascending order
                                  
      $cars = array("Volvo", "BMW", "Toyota");
      sort($cars);
                                  
                                
    rsort() sort arrays in descending order
                                  
      $numbers = array(4, 6, 2, 22, 11);
      rsort($numbers);
                                  
                                
    asort() sort associative arrays in ascending order, according to the value
                                  
      $age = array("Peter"=>"35", "Ben"=>"37", "Joe"=>"43");
      asort($age);
                                  
                                
    ksort() sort associative arrays in ascending order, according to the key
                                  
      $age = array("Peter"=>"35", "Ben"=>"37", "Joe"=>"43");
      ksort($age);
                                  
                                
    arsort() sorts an associative array in descending order, according to the value
                                  
      $age = array("Peter"=>"35", "Ben"=>"37", "Joe"=>"43");
      arsort($age);
                                
                              
    krsort() sorts an associative array in descending order, according to the key
                                  
      $age = array("Peter"=>"35", "Ben"=>"37", "Joe"=>"43");
      krsort($age);
                                  
                                

PHP Array Functions

Function Description Example
array_chunk() Splits an array into chunks of Array.
                    
$cars=array("Volvo","BMW","Toyota","Honda");
print_r(array_chunk($cars,2));
                    
                  
array_combine() creates an array by using the elements from one "keys" array and one "values" array.
                    
$fname=array("Peter","Ben","Joe");
$age=array("35","37","43");
$c=array_combine($fname,$age);
print_r($c);
                    
                  
array_count_values() Returns an associative array, where the keys are the original array's values, and the values are the number of occurrences
                    
$a=array("A","Cat","Dog","A","Dog");
print_r(array_count_values($a));
                    
                  
array_keys() returns an array containing the keys.
                    
$a=array("Volvo"=>"XC90","BMW"=>"X5");
print_r(array_keys($a));
                    
                  
array_values() returns an array containing all the values of an array.
                    
$a=array("Name"=>"Peter","Age"=>"41","Country"=>"USA");
print_r(array_values($a));
                    
                  
array_merge() merges one or more arrays into one array.
                    
$a1=array("red","green");
$a2=array("blue","yellow");
print_r(array_merge($a1,$a2));
                    
                  
array_push() inserts one or more elements to the end of an array.
                    
$a=array("red","green");
array_push($a,"blue","yellow");
print_r($a);
                    
                  
array_pop() deletes the last element of an array.
                    
$a=array("red","green","blue");
array_pop($a);
print_r($a);
                    
                  
count() returns the number of elements in an array.
                    
$cars=array("Volvo","BMW","Toyota");
echo count($cars);
                    
                  
array_search() The array_search() function searches an array for a given value and returns the key. The function returns the key for val if it is found in the array. It returns FALSE if it is not found. If val is found in the array arr more than once, then the first matching key is returned.
                    
$arr = array("MAC", "WINDOWS","LINUX", "SOLARIS");
$search = "WINDOWS";
echo array_search($search,$arr);
                    
                  

PHP Conditional Statements

  • Conditional statements are used to perform different actions based on different conditions.
    Function Description Example
    if The if statement executes some code if one condition is true.
                                                  
      $t = date("H");
      if ($t < "20" ) { 
        echo "Have a good day!" ; 
      }
                                                  
                                                
    if...else The if...else statement executes some code if a condition is true and another code if that condition is false.
                                                  
      $t = date("H");
      if ($t < "20" ){ 
        echo "Have a good day!" ; 
      }
      else
      { 
        echo "Have a good night!" ; 
      }
                                                  
                                                
    if...elseif...else The if...elseif...else statement executes different codes for more than two conditions.
                                                  
      $t = date("H");
      if ($t < "10" ) { 
        echo "Have a good morning!" ; 
      }
      elseif ($t < "20" ) {
        echo "Have a good day!" ; 
      }
      else {
        echo "Have a good night!" ; 
      }
                                                  
                                                

PHP switch Statement

  • Use the switch statement to select one of many blocks of code to be executed.
    $favcolor = "red"; switch ($favcolor) { case "red": echo "Your favorite color is red!"; break; case "blue": echo "Your favorite color is blue!"; break; case "green": echo "Your favorite color is green!"; break; default: echo "Your favorite color is neither red, blue, nor green!"; }

PHP Loops

  • Loops are used to execute the same block of code again and again, as long as a certain condition is true.
    In PHP, we have the following loop types:
  • while : loops through a block of code as long as the specified condition is true
  • do...while : loops through a block of code once, and then repeats the loop as long as the specified condition is true
  • for : loops through a block of code a specified number of times
  • for...each : loops through a block of code for each element in an array

PHP while Loop

  • The while loop executes a block of code as long as the specified condition is true.

    The example below displays the numbers from 1 to 5:
    $x = 1; while($x <= 5) { echo "The number is: $x <br>" ; $x++; }

PHP do while Loop

  • The do...while loop will always execute the block of code once, it will then check the condition, and repeat the loop while the specified condition is true.

    The example below first sets a variable $x to 1 ($x = 1). Then, the do while loop will write some output, and then increment the variable $x with 1. Then the condition is checked (is $x less than, or equal to 5?), and the loop will continue to run as long as $x is less than, or equal to 5:
    $x = 1; do { echo "The number is: $x <br>"; $x++; } while ($x <= 5);

PHP for Loop

  • The for loop is used when you know in advance how many times the script should run.

    parameters :
    • init counter: Initialize the loop counter value
    • test counter: Evaluated for each loop iteration. If it evaluates to TRUE, the loop continues. If it evaluates to FALSE, the loop ends.
    • increment counter: Increases the loop counter value


    The example below displays the numbers from 0 to 10:
    for ($x = 0; $x <= 10; $x++) { echo "The number is: $x <br>" ; }

PHP for each Loop

  • The foreach loop works only on arrays, and is used to loop through each key/value pair in an array.

    The following example will output the values of the given array ($colors):
    $colors = array("red", "green", "blue", "yellow"); foreach ($colors as $value) { echo "$value <br>"; }

PHP Break

  • PHP Break is used to jump out of loop
                  
      $x = 0;
      
      while($x < 10)
      { 
        if ($x==4) 
        { 
          break; 
        } 
        echo "The number is: $x";
        $x++; 
      }
                  
                

PHP continue

  • The continue statement breaks one iteration (in the loop), if a specified condition occurs, and continues with the next iteration in the loop.
                  
      for ($x = 0; $x < 10; $x++) 
      { 
        if ($x==4) 
        { 
          continue; 
        } 
        echo "The number is: $x"; 
      }
                  
                

PHP Functions

  • PHP has over 1000 built-in functions that can be called directly
  • A user-defined function declaration starts with the word function :
                  
      function writeMsg() {
      echo "Hello world!";
      }
      
      writeMsg();
                  
                

PHP Function Arguments

  • Information can be passed to functions through arguments. An argument is just like a variable.
  • If we call the function without arguments it takes the default value as argument:
    function familyName($fname = "mark") { echo "$fname Refsnes. <br>"; } familyName("Jani"); familyName(); familyName("Stale"); familyName("Kai Jim"); familyName("Borge");

PHP Strict

  • NOT USING STRICT
                  
      function addNumbers(int $a, int $b) {
      return $a + $b;
      }
      echo addNumbers(5, "5 days");
      // since strict is NOT enabled "5 days" is changed to int(5), and it will return 10
                  
                
  • USING STRICT
                  
      declare(strict_types=1);
      function addNumbers(int $a, int $b) {
      return $a + $b;
      }
      echo addNumbers(5, "5 days");
      // since strict is enabled "5 days" is string, and it will return error
                  
                

Passing Arguments by Reference

  • When a function argument is passed by reference, changes to the argument also change the variable that was passed in. To turn a function argument into a reference, the & operator is used:
                  
      function add_five(&$value) {
      $value += 5;
      }
      
      $num = 2;
      add_five($num);
      echo $num;
                  
                

PHP Variables Scope

  • In PHP, variables can be declared anywhere in the script.
  • The scope of a variable is the part of the script where the variable can be referenced/used.
  • PHP has three different variable scopes:
    • local
    • global
    • static
  • A variable declared outside a function has a GLOBAL SCOPE and can only be accessed outside a function:
                  
      $x = 5; // global scope
      function myTest() {
        // using x inside this function will generate an error
        echo "<p>Variable x inside function is: $x</p>";
      }
      myTest();
      echo "<p>Variable x outside function is: $x</p>";
                  
                
  • A variable declared within a function has a LOCAL SCOPE and can only be accessed within that function:
                  
      function myTest() {
        $x = 5; // local scope
        echo "<p>Variable x inside function is: $x</p>";
      }
      myTest();
      // using x outside the function will generate an error
      echo "<p>Variable x outside function is: $x</p>";
                  
                
  • Normally, when a function is completed/executed, all of its variables are deleted. However, sometimes we want a local variable NOT to be deleted. We need it for a further job.
    To do this, use the static keyword when you first declare the variable:
                  
      function myTest() {
        static $x = 0;
        echo $x;
        $x++;
      }
      myTest();
      myTest();
      myTest();
                  
                
  • The global keyword is used to access a global variable from within a function.
    To do this, use the global keyword before the variables (inside the function):
                  
      $x = 5;
      $y = 10;
      function myTest() {
        global $x, $y;
        $y = $x + $y;
      }
      myTest();
      echo $y; // outputs 15