Quick Contact

    Introducing ARRAY

    Arrays in PHP is a type of data structure that allows us to store multiple elements of similar data type under a single variable thereby saving us the effort of creating a different variable for every data. The arrays are helpful to create a list of elements of similar types, which can be accessed using their index or key. Suppose we want to store five names and print them accordingly. This can be easily done by the use of five different string variables. But if instead of five, the number rises to hundred, then it would be really difficult for the user or developer to create so much different variables. Here array comes into play and helps us to store every element within a single variable and also allows easy access using an index or a key.

    An array is created using an array () function in PHP.

    There are basically three types of arrays in PHP:
    • Numeric array: An array with a numeric index. Values are stored and accessed in linear fashion.
    • Associative array: An array with strings as index. This stores element values in association with key values rather than in a strict linear index order.
    • Multidimensional array: An array containing one or more arrays and values are accessed using multiple indices
    Advantage of PHP Array:
    • Less Code: We don’t need to define multiple variables.
    • Easy to traverse: By the help of single loop, we can traverse all the elements of an array.
    • Sorting: We can sort the elements of array.
    There are 3 ways to define array
    Example 1:
    <?php
    $arr=array(10,11,12,13,14,15);
    Echo $arr[0];
    ?>
    
    Example 2:
    <?php
    $arr[]=10;
    $arr[]=20;
    $arr[]=30;
    $arr[]=40;
    $arr[]=50;
    Echo $arr[0];
    ?>
    
    Example 3:
    <?php
    $arr[0]=10;
    $arr[1]=20;
    $arr[2]=30;
    $arr[3]=40;
    $arr[4]=50;
    Echo $arr[0];
    ?>
    
    How to use an important programming construct: arrays

    Like most programming languages, PHP lets you create arrays. An array is a special type of variable that can hold many values at once, all accessible via a single variable name. Arrays are very useful whenever you need to work with large amounts of data — such as records from a database — or group related data together.

    How arrays work
    • As you’ve seen already, arrays are variables that can hold more than one value. Here are some more key facts about arrays in PHP:
    • An array can hold any number of values, including no values at all.
    • Each value in an array is called an element.
    • You access each element via its index, which is a numeric or string value. Every element in an array has its own unique index.
    • An element can store any type of value, such as an integer, a string, or a Boolean. You can mix types within an array — for example, the first element can contain an integer, the second can contain a string, and so on.
    • An array’s length is the number of elements in the array.
    • An array element’s value can itself be an array. This allows you to create multidimensional arrays.
    Why arrays are useful

    Arrays in PHP offer many benefits, including the following:

    • They’re easy to manipulate. It’s easy to add or remove elements in an array, as well as read or change the value of an element.
    • It’s easy to work with many values at once. You can easily loop through all elements in an array, reading or changing each element’s value as you move through the loop.
    • PHP gives you many handy array-related functions. For example, you can sort array elements quickly and easily; search arrays for particular values or indices; and merge arrays together.
    How to create an array in PHP

    It’s easy to create an array within a PHP script. To create an array, you use the array() construct:

    $myArray = array( values );
    
    How to use Array in PHP:

    Make Your Code Shorter

    The function list (), which is not really a function, but a language construction, is designed to assign variables in a short way. For example, here is a basic example of using the list() function:

    // define array
    $array = ['a', 'b', 'c'];
    // without list()
    $a = $array[0];
    $b = $array[1];
    $c = $array[2];
    // with list()
    list($a, $b, $c) = $array;
    

    Also, list () can be used with foreach, which makes this construction even better:

    $arrays = [[1, 2], [3, 4], [5, 6]];
     
    foreach ($arrays as list($a, $b)) {
        $c = $a + $b;
        echo($c . ', '); // 3, 7, 11, 
    }
    
    Filtering Functions

    There is a great function for array filtering, and it is called array_filter(). Pass the array as the first param and an anonymous function as the second param. Return true in a callback function if you want to leave this element in the array, and false if you don’t:

    $numbers = [20, -3, 50, -99, 55]; 
    $positive = array_filter($numbers, function($number) {
        return $number > 0;
    });
    print_r($positive); // [0 => 20, 2 => 50, 4 => 55]
    

    There is a way to filter not only by the values. You can use ARRAY_FILTER_USE_KEY or ARRAY_FILTER_USE_BOTH as a third parameter to pass the key or both value and key to the callback function.

    Also, you can call array_filter() without a callback to remove all empty values:

    $numbers = [-1, 0, 1];
    $not_empty = array_filter($numbers); 
    print_r($not_empty); // [0 => -1, 2 => 1]
    
    Walking Through the Arrays

    Using array_map(), you can apply a callback to every element of an array. You can pass a function name or anonymous function to get a new array based on the given array:

    $cities = ['Berlin', 'KYIV', 'Amsterdam', 'Riga'];
    $aliases = array_map('strtolower', $cities);
    print_r($aliases); // ['berlin', 'kyiv, 'amsterdam', 'riga']
    $numbers = [1, -2, 3, -4, 5];
    $squares = array_map(function($number) {
        return $number ** 2;
    }, $numbers);
    print_r($squares);  // [1, 4, 9, 16, 25]
    
    Joining the Arrays

    The best way to merge two or more arrays in PHP is to use the array_merge() function. Items of arrays will be merged together, and values with the same string keys will be overwritten with the last value:

    $array1 = ['a' => 'a', 'b' => 'b', 'c' => 'c'];
    $array2 = ['a' => 'A', 'b' => 'B', 'D' => 'D'];
    $merge = array_merge($array1, $array2);
    print_r($merge);
    // Array
    // (
    //     [a] => A
    //     [b] => B
    //     [c] => c
    //     [D] => D
    // )
    
    Do the Math With Array Values

    Use array_sum() to get a sum of array values, array_product() to multiply them, or create your own formula with array reduce():

    $numbers = [1, 2, 3, 4, 5]; 
    echo(array_sum($numbers)); // 15
    echo(array_product($numbers)); // 120 
    echo(array_reduce($numbers, function($carry, $item) {
        return $carry ? $carry / $item : 1;
    })); // 0.0083 = 1/2/3/4/5
    

    To count all the values of an array, use array_count_values(). It will give all unique values of a given array as keys and a count of these values as a value:

    $things = ['apple', 'apple', 'banana', 'tree', 'tree', 'tree'];
    $values = array_count_values($things);
    print_r($values);
    // Array
    // (
    //     [apple] => 2
    //     [banana] => 1
    //     [tree] => 3
    //
    
    Types of arrays
    • Numerically Indexed arrays
    • Non-Numerically Indexed arrays (Associative Array)
    • Multidimensional arrays
    Numerically Indexed arrays

    These arrays can store numbers, strings and any object but their index will be represented by numbers. By default array index starts from zero. We can store number, string and object in the PHP array.

    In an indexed or numeric array, the indexes are automatically assigned and start with 0, and the values can be any data type.

    Numeric arrays use number as access keys. An access key is a reference to a memory slot in an array variable. The access key is used whenever we want to read or assign a new value an array element.

    There are two ways to create numerically indexed arrays:

    The index can be assigned automatically (index always starts at 0), like this:

    <?php
    // Define an indexed array
    $colors = array("Red", "Green", "Blue"); 
    ?>
    

    or the index can be assigned manually:

    <?php
    $colors[0] = "Red"; 
    $colors[1] = "Green"; 
    $colors[2] = "Blue"; 
    ?>
    
    Example:

    Following is the example showing how to create and access numeric arrays.

    Here we have used array () function to create array.

        <?php
            /* First method to create array. */
            $numbers = array( 1, 2, 3, 4, 5);
            foreach( $numbers as $value ) {
                echo "Value is $value <br />";
            }
            /* Second method to create array. */
            $numbers[0] = "one";
            $numbers[1] = "two";
            $numbers[2] = "three";
            $numbers[3] = "four";
            $numbers[4] = "five";
            foreach( $numbers as $value ) {
            echo "Value is $value <br />";
            }
        ?>
    </body>
    </html>
    
    This will produce the following result:

    Value is 1
    Value is 2
    Value is 3
    Value is 4
    Value is 5
    Value is one
    Value is two
    Value is three
    Value is four
    Value is five

    Loop Through an Numerically Indexed Array:

    To loop through and print all the values of an indexed array, you could use a for loop, like this:

    <!DOCTYPE html>
    <html>
    <body>
        <?php
            $cars = array("Volvo", "BMW", "Toyota");
            $arrlength = count($cars);
            for($x = 0; $x < $arrlength; $x++) {
                echo $cars[$x];
                echo "<br>";
            }
        ?>
    </body>
    </html>
    
    This will produce the following result:

    Volvo
    BMW
    Toyota

    Non-Numerically Indexed arrays (Associative Array)

    The associative arrays are very similar to numeric arrays in term of functionality but they are different in terms of their index. Associative array will have their index as string so that you can establish a strong association between key and values.

    In an associative array, the keys assigned to values can be arbitrary and user defined strings. In the following example the array uses keys instead of index numbers:

    <?php
    // Define an associative array
    $ages = array("Peter"=>22, "Clark"=>32, "John"=>28);
    ?>
    

    The following example is equivalent to the previous example, but shows a different way of creating associative arrays:

    <?php
    $ages["Peter"] = "22";
    $ages["Clark"] = "32";
    $ages["John"] = "28";
    ?>
    
    Example:

    To store the salaries of employees in an array, a numerically indexed array would not be the best choice. Instead, we could use the employees names as the keys in our associative array, and the value would be their respective salary.

    <html>
    <body>
        <?php
            /* First method to associate create array. */
            $salaries = array("mohammad" => 2000, "qadir" => 1000, "zara" => 500);
            echo "Salary of mohammad is ". $salaries['mohammad'] . "<br />";
            echo "Salary of qadir is ".  $salaries['qadir']. "<br />";
            echo "Salary of zara is ".  $salaries['zara']. "<br />";
            /* Second method to create array. */
            $salaries['mohammad'] = "high";
            $salaries['qadir'] = "medium";
            $salaries['zara'] = "low";
            echo "Salary of mohammad is ". $salaries['mohammad'] . "<br />";
            echo "Salary of qadir is ".  $salaries['qadir']. "<br />";
            echo "Salary of zara is ".  $salaries['zara']. "<br />";
        ?>
    </body>
    </html>
    
    This will produce the following result:

    Salary of mohammad is 2000
    Salary of qadir is 1000
    Salary of zara is 500
    Salary of mohammad is high
    Salary of qadir is medium
    Salary of zara is low

    Loop Through an Associative Array

    To loop through and print all the values of an associative array, you could use a foreach loop, like this:

    <html>
    <body>
        <?php
            $age = array("Peter"=>"35", "Ben"=>"37", "Joe"=>"43");
            foreach($age as $x => $x_value) {
            echo "Key=" . $x . ", Value=" . $x_value;
            echo "<br>";
            }
        ?>
    </body>
    </html>
    
    This will produce the following result:

    Key=Peter, Value=35
    Key=Ben, Value=37
    Key=Joe, Value=43

    Multidimensional arrays:

    A multi-dimensional array each element in the main array can also be an array. And each element in the sub-array can be an array, and so on. Values in the multi-dimensional array are accessed using multiple index.

    How to create a multidimensional array

    You can create a multidimensional array using the array () construct, much like creating a regular array. The difference is that each element in the array you create is itself an array.

    For example:
    $myArray = array(
      array( value1, value2, value3 ),
      array( value4, value5, value6 ),
      array( value7, value8, value9 )
    );
    

    An example of a multidimensional array will look something like this:

    <html lang="en">
    <head>
        <title>PHP Multidimensional Array</title>
    </head>
    <body>
        <?php
            // Define nested array
            $contacts = array(
            array(
            "name" => "Peter Parker",
            "email" => "peterparker@mail.com",
            ),
            array(
            "name" => "Clark Kent",
            "email" => "clarkkent@mail.com",
            ),
            array(
            "name" => "Harry Potter",
            "email" => "harrypotter@mail.com",
            )
            );
            // Access nested value
            echo "Peter Parker's Email-id is: " . $contacts[0]["email"];
        ?>
    </body>
    </html>
    
    This will produce the following result:

    Peter Parker’s Email-id is: peterparker@mail.com

    How to Access Elements in Multidimensional Arrays:

    Keys in square brackets are used to access array elements. The first set of square brackets refers to the top-level elements in a multidimensional array. Each subsequent set of square brackets refers to the next level down. The following demonstrates how to access the third element in the ‘vegetables’ sub-array of the $food array defined above:

    echo $food['vegetables'][2]; // cabbage
    

    The following demonstrate how to change the value of the first element in the ‘vegetables’ sub-array:

    $food['vegetables'][0] = 'green beans';
    
    Viewing Array Structure and Values

    You can see the structure and values of any array by using one of two statements — var_dump() or print_r(). The print_r() statement, however, gives somewhat less information. Consider the following example:

    <?php
    // Define array
    $cities = array("London", "Paris", "New York");
    // Display the cities array
    print_r($cities);
    ?>
    
    The print_r() statement gives the following output:
    Array ( [0] => London [1] => Paris [2] => New York )
    

    This output shows the key and the value for each element in the array. To get more information, use the following statement:

    <?php
    // Define array
    $cities = array("London", "Paris", "New York");
    // Display the cities array
    var_dump($cities);
    ?>
    
    This var_dump() statement gives the following output:
    array(3) { [0]=> string(6) "London" [1]=> string(5) "Paris" [2]=> string(8) "New York" }
    

    This output shows the data type of each element, such as a string of 6 characters, in addition to the key and value.

    Array sorting
    What is sorting?

    Sorting refers to ordering data in an alphabetical, numerical order and increasing or decreasing fashion according to some linear relationship among the data items. Sorting greatly improves the efficiency of searching.

    PHP comes with a number of built-in functions designed specifically for sorting array elements in different ways like alphabetically or numerically in ascending or descending order.

    Here we’ll explore some of these functions most commonly used for sorting arrays:

    • sort() : sort arrays in ascending order
    • rsort() : sort arrays in descending order
    • asort() : sort associative arrays in ascending order, according to the value
    • ksort() : sort associative arrays in ascending order, according to the key
    • arsort() : sort associative arrays in descending order, according to the value
    • krsort() : sort associative arrays in descending order, according to the key
    Sorting Indexed Arrays in Ascending Order

    The sort() function is used for sorting the elements of the indexed array in ascending order (alphabetically for letters and numerically for numbers).

    The following example sorts the elements of the $cars array in ascending alphabetical order:
    <html>
    <body>
    <?php
        $cars = array("Volvo", "BMW", "Toyota");
        sort($cars);
        $clength = count($cars);
        for($x = 0; $x < $clength; $x++) {
            echo $cars[$x];
            echo "<<br>";
        }
    ?>
    </body>
    </html>
    
    This will produce the following result:

    BMW
    Toyota
    Volvo

    The following example sorts the elements of the $numbers array in ascending numerical order:
    <!DOCTYPE html>
    <html>
    <body>
        <?php
            $numbers = array(40, 61, 2, 22, 13);
            sort($numbers);
            $arrlength = count($numbers);
            for($x = 0; $x < $arrlength; $x++) {
            echo $numbers[$x];
            echo "<br>";
            }
        ?>
    </body>
    </html>
    
    This will produce the following result:

    2
    13
    22
    40
    61

    Sorting Indexed Arrays in Descending Order

    The rsort () function is used for sorting the elements of the indexed array in descending order (alphabetically for letters and numerically for numbers).

    The following example sorts the elements of the $cars array in descending alphabetical order:
    <html>
    <body>
        <?php
            $cars = array("Volvo", "BMW", "Toyota");
            rsort($cars);
            $clength = count($cars);
            for($x = 0; $x < $clength; $x++) {
                echo $cars[$x];
                echo "<br>";
            }
        ?>
    </body>
    </html>
    
    This will produce the following result:

    Volvo
    Toyota
    BMW

    The following example sorts the elements of the $numbers array in descending numerical order:
    <!DOCTYPE html>
    <html>
    <body>
        <?php
            $numbers = array(40, 61, 2, 22, 13);
            rsort($numbers);
            $arrlength = count($numbers);
            for($x = 0; $x < $arrlength; $x++) {
                echo $numbers[$x];
                echo "<br>";
            }
        ?>
    </body>
    </html>
    
    This will produce the following result:

    61
    40
    22
    13
    2

    Sort Array (Ascending Order), According to Value – asort ()

    The asort () function sorts the elements of an associative array in ascending order according to the value. It works just like sort (), but it preserves the association between keys and its values while sorting.

    The following example sorts an associative array in ascending order, according to the value:
    <html>
    <body>
        <?php
            $age = array("Peter"=>"35", "Ben"=>"37", "Joe"=>"43");
            asort($age);
            foreach($age as $x => $x_value) {
                echo "Key=" . $x . ", Value=" . $x_value;
                echo "<br>";
            }
        ?>
    </body>
    </html>
    
    This will produce the following result:

    Key=Peter, Value=35
    Key=Ben, Value=37
    Key=Joe, Value=43

    Sort Array (Ascending Order), According to Key – ksort()

    The ksort() function sorts the elements of an associative array in ascending order ascending to the key. It preserves the association between keys and its values while sorting, same as asort() function.

    The following example sorts an associative array in ascending order, according to the key:
    <html>
    <body>
        <?php
            $age = array("Peter"=>"35", "Ben"=>"37", "Joe"=>"43");
            ksort($age);
            foreach($age as $x => $x_value) {
                echo "Key=" . $x . ", Value=" . $x_value;
                echo "<br>";
            }
        ?>
    </body>
    </html>
    
    This will produce the following result:

    Key=Ben, Value=37
    Key=Joe, Value=43
    Key=Peter, Value=35

    Sort Array (Descending Order), According to Value – arsort ()

    The arsort() function sorts the elements of an associative array in descending order according to the value. It works just like rsort(), but it preserves the association between keys and its values while sorting.

    The following example sorts an associative array in descending order, according to the value:
    <html>
    <body>
        <?php
            $age = array("Peter"=>"35", "Ben"=>"37", "Joe"=>"43");
            arsort($age);
            foreach($age as $x => $x_value) {
                echo "Key=" . $x . ", Value=" . $x_value;
                echo "<br>";
            }
        ?>
    </body>
    </html>
    
    This will produce the following result:

    Key=Joe, Value=43
    Key=Ben, Value=37
    Key=Peter, Value=35

    Sort Array (Descending Order), According to Key – krsort()

    The krsort() function sorts the elements of an associative array in descending order ascending to the key. It preserves the association between keys and its values while sorting, same as arsort() function.

    The following function sorts an associative array in descending order, according to the key.
    <html>
    <body>
        <?php
            $age = array("ayush"=>"23", "shankar"=>"47", "kailash"=>"41");
            krsort($age);
             
            foreach($age as $x => $x_value) {
                echo "Key=" . $x . ", Value=" . $x_value;
                echo "<br>";
            }
        ?>
    </body>
    </html>
    
    This will produce the following result:

    Key=Shankar, Value=47
    Key=Kailash, Value=41
    Key=Ayush, Value=23

    Summary

    The points below Summarize the topic discussed:

    • An array is a special variable, which can hold more than one value at a time.
    • In PHP, the array() function is used to create an array
    • In PHP, there are three types of arrays Indexed arrays, Associative arrays and Multidimensional arrays.
    • The elements in an array can be sorted in alphabetical or numerical order, descending or ascending.

    Enrolled Courses – PHP Training

    Copyright 1999- Ducat Creative, All rights reserved.