The lesson will cover the possibilities of working with arrays in PHP, declaring an array, types of arrays: multidimensional and associative arrays

  1. Arrays with numeric indexes
  2. $fruits="apple"; $fruits="pear"; $fruits="orange"; $fruits="apricot";

    This option for array initialization is practically not used today. The following option for working with arrays is used:

  3. Associative Array
  4. This option for creating an array uses an array object:

    $fruits = array(1 => "apple", 2 => "pear", 3 => "orange", 4 => "apricot"); // Beginning with PHP versions 5.4 $fruits = array[ 1 => "apple", 2 => "pear", 3 => "orange", 4 => "apricot" ];

    Accessing Array Elements

    1 2 3 4 5 6 7 8 $fruits [ 0 ] = "apple" ; $fruits [ 1 ] = "pear" ; $fruits [ 2 ] = "orange" ; $fruits [ 3 ] = "apricot" ; echo "The first element of the array is ". $fruits[0]. "
    " ; echo "The second element of the array is ". $fruits[1]. "
    " ; echo "The third element of the array is ". $fruits[2]. "
    " ;

    $fruits="apple"; $fruits="pear"; $fruits="orange"; $fruits="apricot"; echo "The first element of the array is ". $fruits."
    "; echo "The second element of the array is ". $fruits ."
    "; echo "The third element of the array is ". $fruits ."
    ";

    The result of executing the program will be:

    Important: The index of an element in an associative array can be not a number, but a word (type string)

    Let's look at an example:

    Example: Create an array student with the values ​​of the first, last names and ages of students. Display the values ​​of array elements

    $student = array("Name" => John, "Surname" => Smith, "Age" => 20); echo "username" . $student["Name"] . "


    ";

    $student["Name"] = "John"; $student["Surname"] = "Smith"; $student["Age"] = 20; echo "username" . $student["Name"] . "
    "; echo "user's last name " . $student["Surname"] . "
    "; echo "user age " . $student["Age"] . "
    ";

    Result:

    Important: String keys (indexes) must always be enclosed in quotes

    Indexed arrays without a key:

    It should also be taken into account that indexes in the array do not need to be written at all when initializing the array with values. Then we create the so-called array-collection(collection object):

    $student = array ("John" , "Smith" , 20 ) ;

    $student = array("John","Smith", 20);

    In this case, the interpreter itself will assign them numerical indices, starting from 0

    Example type conversions and element rewriting.
    Note the use of the var_dump() procedure

    1 2 3 4 5 6 7 8 9 "a" , "1" => "b" , 2 => "c" , 2 => "d" , ) ; var_dump ($my_array) ; ?>

    "a", "1"=> ​​"b", 2 => "c", 2 => "d",); var_dump($my_array); ?>

    Result:

    Array(3) ( => string(1) "a" => string(1) "b" => string(1) "d" )

    Example use multidimensional array and organizing access to its elements

    1 2 3 4 5 6 7 8 9 10 11 12 "1" , 2 => 2 , "multi" => array ( "1_1" => "1_1" ) ) ; var_dump($array_odnom["first"]); var_dump($array_odnom[2]); var_dump($array_odnom["multi"]["1_1"]); ?>

    "1", 2 => 2, "multi" => array("1_1" => "1_1")); var_dump($array_odnom ["first"]); var_dump($array_odnom); var_dump($array_odnom ["multi"]["1_1"]); ?>

    Result:

    String(1) "1" int(2) string(3) "1_1"

    Example: create two-dimensional array dimension 3 x 2. Fill it with the values ​​for the first line: “1_1”, “1_2”, “1_3”; for the second line: “2_1”, “2_2”, “2_3”. Display the first element of an array


    Performance:
    1 2 3 4 5 6 7 8 9 10 11 12 $array_odnom = array ( 1 => array ( 1 => "1_1" , 2 => "1_2" , 3 => "1_3" ) , 2 => array ( 1 => "2_1" , 2 => "2_2" , 3 => "2_3" ) , ) ; echo $array_odnom [ 1 ] [ 1 ] ;

    $array_odnom = array(1 => array(1 => "1_1", 2 => "1_2", 3 => "1_3"), 2 => array(1 => "2_1", 2 => "2_2" , 3 => "2_3")),); echo $array_odnom;

    Job php2_1: create a two-dimensional 3 x 3 array - the upper left corner of the Pythagorean multiplication table (1, 2, 3; 4, 6, 8 ...)



    Laboratory work:
    Let's say you have some kind of ad and several different people to whom you need to send this ad. To do this, you make a template with the content of the ad, inside of which there are a number of changing parameters: an array of people’s names and an array of events. Display one version of the final ad on the screen. To define arrays, use an associative array.

    Use the ad template and focus on the colors:

    Red – arrays.
    Brown – numeric variable.
    Blue – constant.

    Dear Ivan Ivanovich!
    We invite you to Open Day.
    Event date: May 12.
    Best regards, Vasily.


    Complete the code:
    1 2 3 4 5 6 7 8 9 10 11 12 13 14 // declaration of a constant define("SIGN" , "Sincerely, Vasya") ; // array for recipient names$names = array (... ) ; // array for events$events = array("op_doors" => "Open Day", "vistavka" => "exhibition", ... ) ; $str = "Dear $names!
    "
    ; $str .= ...; $str .= ...; echo ...;

    // declaration of a constant define("SIGN","Regards, Vasya"); // array for recipient names $names = array(...); // array for events $events = array("op_doors" => "open day", "vistavka" => "exhibition", ...); $str = "Dear $names!
    "; $str .= ...; $str .= ...; echo ...;

Good day, habrazhiteliki!

In my article I want to talk about processing multidimensional associative arrays in PHP. In my opinion, it is not always convenient to receive necessary information from a multidimensional array. It's one thing if the array is two-dimensional:

array("key1" => "value1", "key2" => "value2")); ?>

Then, of course, it’s easy to get the values ​​we’re interested in:

Echo $array["dimension1"]["key1"]; // value1

But what if we have an n-dimensional array? For example, five-dimensional:

$array = array("dimension1" => array("dimension2" => array("dimension3" => array("dimension4" => array("dimension5" => array("value1" => "Hey! I\ "m value1", "value2" => "Hey! I\"m value2"))))));

To get the value by key, for example, “value1”, we need to write the following code:

Echo $array["dimension1"]["dimension2"]["dimension3"]["dimension4"]["dimension5"]["value1"]; // Hey! I"m value1

I would not call such a recording beautiful, although it is correct. I suggest making this notation a little nicer by making it look like this:

Echo easyA($array)->dimension1->dimension2->dimension3->dimension4->dimension5->value1; // Hey! I"m value1

Agree, it really looks much nicer compared to the standard recording.

So, first we need to create a class that will process our array. Let's call it easyArray and make it a Singleton:

Code

class easyArray( private static $instance; // Class state. private $Array; // Array that was passed to the class. private function __construct())( // Filed out the constructor. ) private function __clone())( // Filed out the cloning method. ) public static function getInstance())( if(null === self::$instance)( self::$instance = new self(); ) return self::$instance; )

After our class has become a singleton, we will add a very important method to it, which will write the resulting array into a private variable:

Code

public function loadArray($newArray)( if(is_array($newArray))( $this->Array = $newArray; return $this; )else( $error = "Sorry, you did not pass an array."; throw new Exception( $error); ) )
From the code you can see that we also check what was passed to the method input. If it was not an array that was passed, we will simply throw an exception with the error " Unfortunately, you did not pass an array". If the check was successful, then we write the resulting array to a private variable and return the current object.

Well, now we will override the magic method "__get()" of our class. This is necessary in order to get the result we want. So:

Code

public function __get($index)( if(isset($this->Array[$index]))( if(is_array($this->Array[$index]))( $this->loadArray($this-> Array[$index]); return $this; )else( return $this->Array[$index]; ) )else( $error = "Missing key (".$index.") in array"; throw new Exception ($error); ) )

First of all, we check the presence of the requested key in the array; if it is not there, we throw an exception with the error " "Missing key (".$index.") in array"". Next, we check whether the requested key is an array. If there is a value for such a key in the array, then we simply return this value. And if it is an array, then we send it to the " loadArray($newArray)" and return the current object ($this).

And How finishing touch of our class, let's add a method that will return the current array that our class works with:

Code

public function arrayReturn() ( return $this->Array; )

So our class is ready, but to get the values ​​we now have to use code like this:

Echo easyArray::getInstance()->loadArray($array)->dimension1->dimension2->dimension3->dimension4->dimension5->value1; // Hey! I"m value1

It became even longer than it was. But this problem can be solved, and for this we need a simple function:

Function easyA($newArray)( return easyArray::getInstance()->loadArray($newArray); )

Well, now let’s check what we got as a result:

Code

array("dimension2" => array("dimension3" => array("dimension4" => array("dimension5" => array("value1" => "Hey! I\"m value1", "value2" => "Hey! I\"m value2")))))); require_once("easyArray.php"); require_once("easyArrayFunction.php"); echo easyA($array)->dimension1->dimension2->dimension3->dimension4->dimension5->value1; // Hey! I\"m value1 echo easyA($array)->dimension1->dimension2->dimension3->dimension4->dimension5->value2; // Hey! I\"m value2 ?>
Everything works as intended.

In addition, this class can be passed configuration files like:

Code

array("dimension2" => array("dimension3" => array("dimension4" => array("dimension5" => array("value1" => "Hey! I\"m value1 from file array.php", "value2" => "Hey! I\"m value2 from file array.php")))))); ?>


To do this you need to use the following construction:

Code

echo easyA(require_once("array.php"))->dimension1->dimension2->dimension3->dimension4->dimension5->value1; // Hey! I"m value1 from file array.php

I may have reinvented the wheel, but I think this article will be of interest to both beginners and other programmers.

Thank you for your attention.

An array does not have to be a simple list of keys and simple values. Each element of an array can contain as a value another array, which in turn can also contain an array, and so on. This way you can create two-dimensional and three-dimensional arrays.

Two-dimensional arrays

Two-dimensional array- an array that stores other arrays as values. Consider creating a two-dimensional array using the array() constructor:

$flowers = array(array("roses", 100 , 15), array("tulips", 60 , 25), array("orchids", 180 , 7));

The $flowers array contains three arrays. As you remember, to access the elements of a one-dimensional array, you must specify the array name and key. The same is true for two-dimensional arrays, with one exception: each element has two keys: the first to select a row, the second to select a column.

To display the elements of this array, you can manually assign access to each of them, but it is better to use nested loops:

Manual access to elements
"; echo $flowers." price ".$flowers." number of ".$flowers."
"; echo $flowers." price ".$flowers." number of ".$flowers."
"; echo "

Using Loops to Print Elements

"; echo "
    "; for ($row = 0; $row< 3; $row++) { echo "
  1. Row number $row"; echo "
      "; for ($col = 0; $col< 3; $col++) { echo "
    • ".$flowers[$row][$col]."
    • "; ) echo "
    "; echo "
  2. "; ) echo "
"; ?>

Instead of column numbers (indexes assigned to them by default), you can assign the necessary keys to them. Associative arrays are used for this purpose. The following array will store the same data, but using keys to name the columns of information:

$flowers = array(array("Name" => "roses", "Price" => 100, "Quantity" => 15), array("Name" => "tulips", "Price" => 60, " Quantity" => 25,), array("Name" => "orchids", "Price" => 180, "Quantity" => 7));

Keys create additional convenience for working with an array in cases where you need to get one of the values. The data you need can be easily found by accessing the correct cell using meaningful row and column names. However, in this case we lose the ability to sequentially traverse the array using for loop.

We can only iterate over child arrays using a for loop. Since they, in turn, are associative, to iterate over their elements you need to use a foreach loop, or iterate over the elements manually:

"roses", "Price" => 100, "Quantity" => 15), array("Name" => "tulips", "Price" => 60, "Quantity" => 25,), array("Name " => "orchids", "Price" => 180, "Quantity" => 7)); echo "

Manual access to elements associative array

"; for ($row = 0; $row< 3; $row++) { echo $flowers[$row]["Название"]." цена ".$flowers[$row]["Цена"] ." количество ".$flowers[$row]["Количество"]; echo "
"; ) echo "

Using a foreach loop to access elements

"; echo "
    "; for ($row = 0; $row< 3; $row++) { echo "
  1. Row number $row"; echo "
      "; foreach($flowers[$row] as $key => $value) ( ​​echo "
    • ".$value."
    • "; ) echo "
    "; echo "
  2. "; ) echo "
"; ?>

It is not necessary to use the array() constructor to create a two-dimensional array; you can also use the short syntax - square brackets:

$flowers = [ [ "Name" => "roses", "Price" => 100, "Quantity" => 15 ], [ "Name" => "tulips", "Price" => 60, "Quantity" = > 25, ], [ "Name" => "orchids", "Price" => 180, "Quantity" => 7 ] ];

Three-dimensional arrays

You don't have to limit yourself to just two dimensions: just as array elements can contain arrays, those arrays in turn can contain new arrays.

A three-dimensional array characterizes width, height and depth. If you represent a two-dimensional array as a table, then a three-dimensional array adds layers to this table. Each element of such an array will refer to a layer, row and column.

If you slightly modify our array with flowers, you can convert it into three-dimensional. In the code below you can see that three-dimensional array- an array containing an array of arrays:

$flowers = [ [ ["roses", 100 , 15], ["tulips", 60 , 25], ["orchids", 180 , 7] ], [ ["roses", 100 , 15], ["tulips" ", 60, 25], ["orchids", 180, 7], ], [ ["roses", 100, 15], ["tulips", 60, 25], ["orchids", 180, 7] ] ];

Since this array only contains numeric indices, we can use nested loops to display it:

"; for ($layer = 0; $layer< 3; $layer++) { echo "

  • Layer number $layer"; echo "
      "; for ($row = 0; $row< 3; $row++) { echo "
    • Row number $row"; echo "
        "; for ($col = 0; $col< 3; $col++) { echo "
      • ".$flowers[$layer][$row][$col]."
      • "; ) echo "
      "; echo "
    • "; ) echo "
    "; echo "
  • "; ) echo ""; ?>

    $arr [ 1 ] = "PHP" ;
    $arr [ 2 ] = "MySQL" ;
    $arr [ 3 ] = "Apache" ;
    ?>

    Array elements can be used in double quotes both ordinary variables and code

    echo " $arr [ 1 ] $arr [ 2 ] $arr [ 3 ] " ;
    ?>

    $arr [ "first" ] = "PHP" ;
    $arr [ "second" ] = "MySQL" ;
    $arr [ "third" ] = "Apache" ;
    ?>

    In this case the array is called associative, and its indices are called keys. To display an array element in a string, quotes (neither double nor single) should not be specified:

    echo " $arr [ first ] $arr [ second ] $arr [ third ] " ;
    ?>

    Since associative arrays do not have indexes, a special type of loop has been introduced to traverse them - foreach:

    foreach($arr as $key => $value )
    {
    echo " $key = $value
    " ;
    }
    ?>

    As a result of the loop, three lines will be output

    First = PHP
    second = MySQL
    third = Apache

    The "$key =>" construction, which allows access to the array key on each of the loops, is optional and can be omitted:

    foreach($arr as $value )
    {
    echo " $value
    " ;
    }
    ?>

    A number of functions also allow you to return arrays, for example, the function file(), which reads a file and returns its contents as an array. Each element of the array corresponds to one line.

    $arr = file("text.txt");
    for($i = 0 ; $i< count ($arr ); $i ++)
    {
    echo $arr [ $i ]. "
    " ;
    }
    ?>

    Another useful feature is the function explode(), which allows you to split a string into several fragments, each of which fits into separate element array:

    $str = "345|[email protected]|http://www.site|login|password";
    $arr = explode ("|" , $str );
    for($i = 0 ; $i< count ($arr ); $i ++)
    {
    echo $arr [ $i ]. "
    " ;
    }
    ?>

    The result of the script might look like this:

    345
    [email protected]
    http://www.site
    login
    password

    There is also an inverse function - implode(), which combines array elements into a string using a given delimiter:

    $arr = "345" ;
    $arr = " [email protected]" ;
    $arr = "http://www.site" ;
    $arr = "login" ;
    $arr = "password" ;
    $str = implode ("##" , $arr );
    echo $str ; //345##[email protected]##http://www.
    ?>

    Comment

    In general, there are a great many functions that gut a string; consideration of all of them is beyond the scope of this article.

    You can remove a single element of an array using the function unset(), and you can check the existence of an array using the function isset(). Let's define an array of 10 elements and destroy every even element.

    unset($arr [ 0 ], $arr [ 2 ], $arr [ 4 ], $arr [ 6 ], $arr [ 8 ]);
    // Check if array elements exist
    for($i = 0 ; $i< 10 ; $i ++)
    {
    if(isset($arr [ $i ])) echo "The element $arr [ $i ] is defined
    " ;
    else echo "Element $arr [ $i ] indefined
    "
    ;
    }
    ?>

    The result of the script from will be the following lines

    The $arr element is undefined
    The $arr element is defined
    The $arr element is undefined
    The $arr element is defined
    The $arr element is undefined
    The $arr element is defined
    The $arr element is undefined
    The $arr element is defined
    The $arr element is undefined
    The $arr element is defined

    Using the function unset() you can destroy the entire array at once.

    $arr = array(9, 8, 7, 6, 5, 4, 3, 2, 1, 0);
    unset($arr);
    if(isset($arr )) echo "Array defined";
    else echo "Array is not defined";
    ?>

    Previously, arrays were dumped using a loop, but PHP provides a special function for dumping an array print_r(). The function is focused on output to a console stream, so when outputting results to a browser window, it is better to frame it with tags

    AND
    :

    $arr = "345";
    $arr = " [email protected]";
    $arr = "http://www.site";
    $arr = "login";
    $arr = "password";
    echo "

    ";
    print_r($arr);
    echo " ";
    ?>

    The result of the script looks like this:

    Array
    => 345
    => [email protected]
    => http://www.site
    => login
    => password
    )

    Multidimensional arrays

    Not only scalar quantities, but also the arrays themselves can act as array elements. In this case, we get the so-called multidimensional arrays.

    Suppose you need to get the following table:

    To do this, let's create a two-dimensional array:

    $arr = array(array('Vasya' , 'locksmith' , 2500 ),
    array('Misha', 'builder', 3000),
    array('Andrey', 'driver', 2700));
    ?>

    Now the table can be displayed using the following code:

    for ($i = 0; $i< 3 ; $i ++)
    {
    for ($j = 0 ; $j< 3 ; $j ++)
    {
    echo " | " . $arr[$i][$j];
    }
    echo "
    " ;
    }
    ?>

    Result:

    | Vasya | locksmith | 2500
    | Misha | builder | 3000
    | Andrey | driver | 2700

    You can also use three-dimensional, four-dimensional, etc. arrays.

    Operations on arrays (collection of recipes)

    1) Determining the number of elements in an array count():

    Let's create an array $name:

    ?>

    To determine the number of elements in an array, you can do the following:

    echo ‘Number of elements in the array- ’ . count($name);
    ?>

    Result:

    Number of elements in the array – 8

    2) Combining arrays

    a) Create two associative arrays $a and $b:

    $a = array(“a” => ”aa” , “b” => “bb” );
    $b = array(“c” => ”cc” , “d” => “dd” );
    ?>

    Suppose you need to create an array $c, which will contain both elements of the array $a and the array $b:

    $a = array("a" => "aa" , "x" => "xx" );
    $b = array("c" => "cc" , "d" => "dd" );
    $c = $a + $b ;
    echo "

    "
    ;
    
    print_r($c);
    echo "
    " ;
    ?>

    Result:

    Array
    [a] => aa
    [x] => xx
    [c] => cc
    [d] => dd
    )

    b) Create two numeric arrays $a and $b:

    $a = array(10, 20);
    $b = array(100 , 200 , 300 , 400 , 500 );
    ?>

    They can no longer be combined using the construction $c = $a + $b;. To combine them you will need to use the function array_merge():

    $c = array_merge ($a, $b);
    ?>

    3) Array sorting

    Let's use the $name array:

    $name = array("Boss" , "Lentin" , "NAV" , "Endless" , "Dragons" , "SiLeNT" , "Doctor" , "Lynx" );
    ?>

    Suppose you want to sort an array in alphabetical order, for this you can use the following code:

    sort($name);
    echo "

    "
    ;
    
    print_r($name);
    echo "
    " ;
    ?>

    Result:

    Array
    => Boss
    => Doctor
    => Dragons
    => Endless
    => Lentin
    => Lynx
    =>NAV
    => SiLeNT
    )

    Suppose you need to select the shortest element (which has the smallest number of characters) from the $name array, in this case you can use the code:

    $name = array("Boss" , "Lentin" , "NAV" , "Endless" , "Dragons" , "SiLeNT" , "Doctor" , "Lynx" );
    $min = strlen($name[0]);
    $nam = $name [ 0 ];
    for ($i = 1 ; $i< count ($name ); $i ++)
    {
    $len = strlen ($name [ $i ]);
    if ($len< $min )
    {
    $nam = $name [ $i ];
    $min = strlen ($nam );
    }
    }
    echo "Shortest length - ". $nam ;
    ?>

    4) Moving inside an array

    Let's create an array $num:

    $num = array(1, 2, 3, 4, 5, 6, 7, 8, 9, 10);
    ?>

    Suppose you want to display the elements of an array in reverse order, in this case you can use the code:

    $end = end($num);
    While ($end)
    {
    echo $end . " - " ;
    $end = prev($num);
    }
    ?>

    Result:

    10 - 9 - 8 - 7 - 6 - 5 - 4 - 3 - 2 – 1

    The above code can be modified:

    $num = range(1, 10);
    print_r(array_reverse($num));
    ?>

    Function range(1,10) creates an array (1,2,3,4,5,6,7,8,9,10) with a random arrangement of elements. Function array_reverse() takes an array and arranges the elements in reverse order (10,9,8,7,6,5,4,3,2,1)

    Functions next(), each() moves the pointer forward one element. Function reset() returns a pointer to 1 element in the array. Let's use the $num array.

    An array is a collection of objects that have the same size and type. Each object in the array is called element of the array. Creating a new array in PHP is easy. When declaring an indexed array, a pair of square brackets () is placed after the variable name:

    $languages ​​= "Spanish";

    // $languages ​​= "Spanish"

    You can then add new elements to the array, as shown below. Please note that new elements are added without explicitly specifying an index. In this case, the new element is added at a position equal to the length of the array plus 1:

    $languages ​​= "English"; // $1anguages[l] = "English";

    $languagest ] = "Gaelic"; // $languages ​​= "Gaelic";

    In addition, new elements can be added to a specific array position. To do this, specify the index of the first element:

    $languages ​​= "Italian";

    $languages ​​= "French";

    Associative arrays are created in a similar way:

    $languages["Spain"] = "Spanish";

    $languages["France"] = "French";

    When creating arrays, three standard language constructs are used:

    • array();
    • list();
    • range().

    Although all three cases result in the same result, creating an array, in some cases one design may be preferable to the others. Below are descriptions and examples of using each design.

    array() function gets zero or more elements and returns an array consisting of the specified elements. Its syntax is:

    array array ([element1, element2...])

    Array() is probably just a more visual shorthand for creating an array, used for programmer convenience. Below is an example of using array() to create an indexable array:

    $languages ​​= array("English". "Gaelic". "Spanish");

    // $languages ​​= "English". $languages ​​= "Gaelic",

    // $languages ​​= "Spanish"

    Here's how array() is used to create associative arrays:

    $languages ​​= array("Spain" => "Spanish",

    "Ireland" => "Gaelic".

    "United States" => "English");

    // $languages["Spain"] = "Spanish"

    // $languages["Ireland"] = "Gaelic"

    // $languages["United States"] = "English"

    Associative arrays are especially useful in situations where numeric indexes do not have a logical correspondence. For example, in the previous example, country names are quite naturally associated with languages. Try to implement this logical connection using numbers!

    The list() construct is similar to array(), but its main purpose is to simultaneously assign values ​​extracted from an array to multiple variables at once. List() command syntax:

    void list (variable1 [. variable2, ...])

    The list() construct is especially useful when reading information from a database or file. Let's say you want to format and output data read from text file. Each line of the file contains information about the user (name,

    profession and favorite color); The components of a record are separated by a vertical bar (|). A typical line looks like this:

    Nino Sanzi|Professional Golfer|green

    Using list(), you can write a simple loop that will read each line, assign its components to variables, and format and display the data. The listing below demonstrates the ability to simultaneously assign to multiple variables using list():

    while ($line = fgets ($user_file. 4096)) :

    // Split the string using split().

    // Components are assigned to Sname variables. $occupation and Scolor.

    list ($name, $occupation, $color) = split("|", $line);

    // Format and output data

    print "Name: Sname
    ";

    print "Occupation: Soccupation
    ";

    print "Favorite color: Scolor
    ";

    Each line of the file is read, formatted, and output as follows:

    Name: Nino Sanzi

    Occupation: Professional Golfer

    Favorite color: green

    In the example above, the use of list() depends on splitting the string into elements using the split() function. The elements resulting from the division are assigned to the variables $name, $occupation, and $color, respectively. Then it all comes down to formatting the data for output in a specific browser. Convenient tools for lexical analysis of text files are one of the strengths PHP. This topic is covered in detail in Chapters 7 and 8.

    The range() construct allows you to quickly and easily create an array of integers from a range defined by an upper and lower bound. Range() returns an array consisting of all integers in the specified range. range() syntax:

    array range (int lower_bound, int upper_bound)

    The following example clearly shows how convenient this design is:

    $lottery = range(0.9);

    // $lottery = array(0,1,2,3,4,5,6,7,8,9)

    As can be seen from the above fragment, the range() parameters specified an interval from 0 to 9 and the $lottery array was filled with integers from this interval.

    Multidimensional arrays

    Over time, your programs will become more complex, and simple one-dimensional arrays will not be enough to store the necessary information. Multidimensional array(array of arrays) provides the programmer with more efficient means for storing information that requires additional structuring. Creating a multidimensional array is easy—just add an extra pair of square brackets to force the array into a new dimension:

    $chessboard = "King"; // Two-dimensional array

    $capitals["USA"] ["Ohio"] = "Columbus": // Two-dimensional array

    $streets["USA"]["Ohio"]["Columbus"] = "Harrison"; // Three-dimensional array

    As an example, consider an array that stores information about desserts and the features of their preparation. It would be quite difficult to get by with a one-dimensional array, but a two-dimensional array fits perfectly:

    $desserts = аrrау(

    "Fruit Cup" => array (

    "calories" => "low",

    "served" -> "cold",

    "preparation" => "10 minutes"

    "Brownies" => array (

    "calories" -> "high",

    "served" => "piping hot",

    "preparation" => "45 minutes"

    After creating an array, its elements can be accessed using the corresponding keys:

    $desserts["Fruit Cup"]["preparation"] // returns "10 minutes"

    $desserts["Brownies"]["calories"] // returns "high"

    Assigning values ​​to elements of multidimensional arrays is performed in the same way as in one-dimensional arrays:

    $desserts["Cake"]["calories"] = "too many";

    // Sets the "calories" property of the "Cake" object to "too many"

    Although multidimensional arrays introduce new levels of logical organization of data, multidimensional arrays are created in much the same way as one-dimensional arrays. However, references to multidimensional arrays in strings require special attention; The next section is devoted to this topic.

    References to multidimensional arrays

    print "Brownies are good, but the calories content is ".

    $desserts["Brownies"]["calories"];

    print "Brownies are good, but the calories content is

    ($desserts)";

    Note the absence of quotation marks around the keys. You should also remember that there should be no extra spaces between the curly braces and the link. If at least one of these conditions is not met, an error will occur. However, both methods are suitable. I recommend choosing one format and sticking with it to make your programs look more consistent. If do not use With any of these formatting methods, references to multidimensional arrays will be interpreted literally, which is likely to lead to unexpected results.

    Finding Array Elements

    Searching for elements is one of the most important operations with arrays. There are several in PHP standard features, allowing you to easily find the necessary keys and values ​​in the array.

    The i n_array() function checks whether a given element is present in the array. If the search is successful, the function returns TRUE, otherwise it returns FALSE. The syntax of the in_array() function is:

    bool in_array(mixed element, array array)

    This function is especially convenient because you do not have to loop through the entire array in search of the desired element. In the following example, the in_array() function looks for the element "Russian" in the $languages ​​array:

    $languages ​​= array("English", "Gaelic", "Spanish"):

    $exists = in_array("Russian", $languages); // $exists is set to FALSE

    $exists = in_array("English", $languages): // $exists is set to TRUE

    The in_array() function is often found in control constructs where its return value (TRUE/FALSE) is used to select one of two continuation options. The following example uses the in_array() function to select one of two options in a conditional if statement:

    // User input

    $language = "French"; $email = " [email protected]";

    // If the language is present in the array

    if (in_array($language. $languages)) :

    // Subscribe the user to the newsletter.

    // Please note: PHP does not have a standard function named

    // subscribe_user(). In this example, this function simply simulates

    // subscription process.

    subscribe_user($email, $language);

    print "You are now subscribed to the $language edition of the newsletter.";

    // Language is not in the array

    print "We"re sorry, but we don"t yet offer a $language edition of the newsletter".

    What's going on in this example? Let's say the $language and $email variables contain user input. You want to make sure that the specified language is supported by your system and use the in_array() function for this purpose. If the language name is present in the array, the user subscribes to the newsletter and receives a corresponding message. Otherwise, the program reports that the newsletter is not distributed in the specified language. Of course, in a real program, the user shouldn't have to guess which languages ​​your program supports. The problem is solved using a drop-down list - this topic is discussed in detail in Chapter 10. Here, this example just demonstrates the capabilities of working with arrays.

    The array_keys() function returns an array containing all the keys of the original array passed as a parameter. If the additional parameter search_item is passed during the call, only the keys that match set value; otherwise, all array keys are returned. The array_keys() function syntax is:

    array array_keys (array array [, mixed search_element])

    Let's look at an example of using the array_keys() function to get the key of a given element:

    $great_wines = array ("Australia" => "Clarendon Hills 96",

    "France" => "Comte George de Vogue 97",

    "Austria" => "Feiler Artinger 97");

    $great_labels = array_keys($great_wines);

    // $great_labels = array("Australia", "France", "Austria");

    $great_labels = array_keys($great_wines, "Clarendon Hills 96");

    // $great_labels = array("Australia");

    The array_keys() function makes it very easy to get all the keys of an associative array - for example, in the previous case they were the names of the countries in which different types of wine are produced.

    The array_values() function returns an array consisting of all the values ​​in the original array passed as a parameter. The array_values() function syntax is:

    array array_values(array array)

    Let's go back to the previous example, where the array_keys() function was used to get all the key values. This time, the array_values() function returns all the values ​​corresponding to the keys:

    // $great_wines = array ("Australia" => "Clarendon Hills 96",

    // "France" => "Comte George de Vogue 97",

    // "Austria" => "Feiler Artinger 97");

    $great_labels = array_values($great_wines);

    // $great_labels = аrrау("Clarendon Hills 96",

    // "Comte George de Vogue 97",

    // "Feiler Artinger 97");

    The array_keys() and array_values() functions complement each other, allowing you to get all the components of one side or another of an associative array if necessary.

    Adding and removing items

    Fortunately, in PHP you don't need to specify a maximum number of elements when creating an array. This gives you more flexibility when you operate on arrays because you don't have to worry about accidentally overrunning the array if the number of elements exceeds an expected threshold. There are several functions in PHP to increase the size of an array. Some of them were created for the convenience of programmers accustomed to working with various types queues and stacks (FIFO, FILO, etc.), which is reflected in the names of the functions (push, pop, shift and unshift). But even if you don't know what a "queue" or "stack" is, don't worry—there's nothing complicated about these functions.

    A queue is a data structure from which elements are retrieved in the order they are received. A stack is a data structure from which elements are retrieved in the reverse order of their arrival.

    The array_push() function appends (that is, appends to the end of the array) one or more new elements. The array_push() function syntax is:

    int array_push(array array, mixed element [, ...])

    The length of an array increases in direct proportion to the number of its elements. This is demonstrated in the following example:

    $languages ​​= array("Spanish", "English", "French");

    array_push($languages, "Russian", "German", "Gaelic");

    // $languages ​​= array("Spanish", "English", "French",

    // "Russian", "German", "Gaelic")

    The array_push() function, like many standard PHP functions, has a “double” - the array_push() function, designed to retrieve elements from an array. The main difference between these functions is that array_push() can add multiple elements at a time, while array_push() only removes elements one at a time.

    array_pop()

    The result of the array_push() function is exactly the opposite of array_push() - this function fetches (that is, removes) the last element from the array. The extracted element is returned by the function. Syntax of the app_op() function:

    array_pop(array array)

    Each time appray_pop() is executed, the size of the array is reduced by 1. Let's look at an example:

    $languages ​​= array("Spanish", "English", "French",

    "Russian", "German", "Gaelic");

    $a_language = array_pop($languages): // $a_language = "Gaelic"

    $a_language = array_pop($languages): // $a_language = "German"

    // $languages ​​= array ("Spanish", "English", "French", "Russian");

    The array_push() and array_pop() functions are useful because they allow you to perform operations on elements and control the size of an array without worrying about uninitialized or empty elements. This solution works much more efficiently than any attempts to control these factors by the programmer.

    The array_shift() function is similar to array_shift() with one difference: the element is removed from the beginning (left edge) of the array. All other elements of the array are shifted one position to the beginning of the array. The array_shift() function has the same syntax as array_shift():

    array_shift(array array)

    When working with the array_shift() function, you need to remember that elements are removed from the beginning of the array, as the following example shows:

    $languages ​​= array("Spanish", "English", "French", "Russian");

    $a_language = array_shift($languages); // $a_language = "Spanish";

    // $languages ​​= array("English", "French", "Russian");

    The array_unshift() function complements array_shift() by inserting a new element at the beginning of the array and shifting the remaining elements one position to the right. The array_unshift() command syntax is:

    1nt array_unshift(array array, mixed variable1 [....variable2])

    With one function call, you can add one or several elements, and the size of the array increases in proportion to the number of added elements. Example of adding multiple elements:

    $ languages ​​= array("French", "Italian", "Spanish");

    array_unshift($languages, "Russian", "Swahili", "Chinese");

    // $languages ​​= array("Russian", "Swahili", "Chinese",

    // "French", "Italian", "Spanish");

    The array_pad() function allows you to quickly grow an array to the desired size by padding it with standard elements. The array_pad() function syntax is:

    array arrap_pad(array array, int size, mixed value):

    Parameter size defines the new length of the array. Parameter meaning specifies the default value assigned to elements at all new positions in the array. There are some things to consider when using array_pad():

    If size is positive, the array is padded on the right, and if negative, the array is padded on the left.

    If the absolute value of the parameter size is less than or equal to the length of the array, no action is performed.

    The absolute value (modulus) of an integer is its unsigned value. For example, the absolute value of the numbers 5 and -5 is 5.

    Example of appending an array from the end:

    $weights = array_pad($weights. 10, 100);

    // Result: $weights = array(1, 3, 5, 10, 15, 25, 50, 100, 100, 100);

    Example of appending an array from the beginning:

    $weights = array(1, 3, 5, 10, 15, 25, 50);

    $weights = array_pad($weights, -10, 100);

    // Result: $weights = array(100, 100, 100, 1, 3, 5, 10, 15, 25, 50);

    Incorrect attempt to append an array:

    $weights = array(1, 3, 5, 10, 15, 25, 50);

    $weights = array_pad($weigtits, 3, 100);

    // The $weights array does not change:

    // $weights = array(1, 3, 5, 10, 15, 25, 50);

    Iterating over elements

    PHP has several standard functions designed to iterate through array elements. Together, these functions provide a flexible and convenient means for quickly processing and displaying the contents of arrays. You'll probably use these functions a lot, since they form the basis of almost all array algorithms.

    The reset() function moves the internal pointer to the current position in the array to the first element. Additionally, it returns the value of the first element. Reset() function syntax:

    mixed reset (array array)

    Consider the following array:

    $fruits = array("apple", "orange", "banana");

    Let's say the current position pointer in this array is set to the element "orange". Team:

    $a_fruit = reset($fruits);

    will return a pointer to the beginning of the array, that is, the element "apple", and will return this value if the result of the reset() call is used in the program. A simplified version of the call is also possible:

    In this case, the pointer moves to the first element of the array and the return value is not used.

    The each() function does two things each time it is called: it returns the key/value pair referenced by the current position pointer, and it moves the pointer to the next element. Each() function syntax:

    array each (array array)

    For convenience, each() returns the key and value as an array of four elements; the keys of this array are 0, 1, value and key. The returned key is associated with keys 0 and key, and the returned value is associated with keys 1 and value.

    In the following example, the each() function returns the element at the current position:

    // Declare an array of five elements

    $spices = array("parsley", "sage", "rosemary", "thyme", "pepper");

    // Set the pointer to the first element of the array

    // Create an array $a_sp1ce. four-piece

    $a_spice = each($spices);

    As a result of executing the above fragment, the $a_spice array will contain the following key/value pairs:

    • 0 => 0;
    • 1 => "parsley";
    • key => 0;
    • value => "parsley".

    After this, the string "parsley" can be output by any of the following commands:

    print $a_spice: print $a_spice["value"];

    The each() function is typically used in combination with list() in looping constructs to iterate through all or some of the elements of an array. On each iteration, each() returns either the next key/value pair or a boolean false when reached last element array. Let's return to the $spices array; To display all elements on the screen, you can use the following script:

    // Reset the current position pointer

    // Enumerate key/value pairs, limiting the output to the value

    while (list ($key, $val) = each ($spices)) :

    print "$val
    "

    Below is a more interesting example of using each() in combination with the other functions described in this chapter. Listing 5.1 shows how to use these functions to display a formatted table of countries and languages.

    Listing 5.1. Building an HTML table from the contents of an array

    // Declare an associative array of countries and languages ​​$languages ​​= array ("Country" => "Language",

    "Spain" => "Spanish",

    "USA" => "English",

    "France" => "French",

    "Russia" => "Russian");

    // Start a new table

    print "

    ";

    // Move the pointer to the position of the first element

    $hdl = key($languages);

    Shd2 = $languages[$hd1];

    // Display the first key and element as table headers

    print "

    ";

    next($languages);

    // Print table rows with keys and array elements

    while (list ($ctry,$lang) = each ($languages)) :

    print "

    ";

    // End the table print "

    $hd1$hd2
    Sctry$lang
    ";

    Running this code will produce the following HTML table.

    Country

    Language

    Spain Spanish
    USA English
    France French
    Russia Russian

    This example gives an idea of ​​PHP's greatest strength - its ability to combine dynamic code with HTML to produce a visual, formatted representation of the data it reads.

    The end() function moves the pointer to the position of the last element of the array. end() function syntax:

    end(array array)

    The next() function moves the pointer forward one position and then returns the element at the new position. If as a result of displacement

    The pointer will go beyond the array, next() returns false. Next() function syntax:

    mixed next (array array)

    The disadvantage of the next() function is that it returns false for existing but empty array elements. If you want to do a regular search, use the each() function.

    The prev() function is similar to next() with one exception: it moves the pointer one position to the beginning of the array, and then returns the element at the new position. If the offset places the pointer before the first element of the array, prev() will return false. The prev() function syntax is:

    mixed prev (array array)

    The disadvantage of the prev() function is that it returns false for existing but empty array elements. If you want to do a regular search, use the each() function.

    The array_walk() function allows you to apply a function to multiple (or possibly all) elements of an array. The array_walk() function syntax is:

    int array_walk(array array, string function_name [, mixed data])

    The function specified by function_name can be used for various purposes, such as finding elements with certain characteristics or modifying the contents of an array. In associative arrays, the function_name function must receive at least two parameters - an array element and a key. If the optional third parameter data is specified, it becomes the third parameter. The following example uses the array_walk() function to remove duplicates from an array:

    function delete_dupes($element) (

    static $last=""; if ($element == $last)

    unset($element); else. ""

    $emails = array(" [email protected]", "[email protected]", "[email protected]");

    array_walk($emails,"delete_dupes");

    // $emails = array(" [email protected]", "[email protected]");

    The array_reverse() function allows you to easily reverse the order of the elements that make up an array. The array_reverse() function syntax is:

    array array_reverse(array array)

    Let's look at an example of using the array_reverse() function:

    $us_wireproducers = array("California", "Oregon", "New York". "Washington");

    $us_wine_producers - array_reverse(Sus_wine_producers);

    // $us_wine_producers = array ("Washington". "New York", "Oregon". "California");

    When you call array_reverse() on an associative array, the key/value pairs are preserved, only the order of the array elements is changed.

    The array_flip() function flips the keys and values ​​of array elements. The array_flip() function syntax is:

    array array_flip(array array)

    In the following example, the array_flip() function swaps all the keys and values ​​of the elements:

    $languages ​​= array("Spain" => "Spanish", "France" => "French", "Italy" => "Italian");

    $languages ​​= array_flip($languages);

    // $languages ​​= array("Spanish" => "Spain", // "French" => "France", // "Italian" => "Italy");

    Remember: array_flip() function doesn't change order of array elements. The array_reverse() function is used for this purpose.

    Array size

    Having information about the current array size can often make a script more efficient. Array size is probably most often used when iterating over elements:

    $us_wine_producers = array("Washington". "New York", "Oregon", "California");

    for (Si = 0; Si< sizeof ($us_wine_producers); $i++) :

    print "$us_wine_producers[$i]";

    Since the $us_wine_producers array is indexed by integers, we can use a for loop to cycle through the counter variable ($i) and print out each element in the array.

    The sizeof() function returns the number of elements in an array. The sizeof() function syntax is:

    int sizeof(array array)

    You'll likely see the sizeof() function a lot in your web applications. Below is a brief example of its use (by the way, the previous example is also a standard use of sizeof()):

    $pasta = array("bowties", "angelhair", "rigatoni");

    $pasta_size = sizeof($pasta);

    // $pasta_size = 3

    The sizeof() function also has another, extended form, count() (see below).

    The count() function performs the same operation as sizeof(); it returns the number of values ​​contained in an array. The count() function syntax is:

    int count (mixed variable)

    The only difference between sizeof() and count() is that in some situations count() returns additional information:

    • if the variable exists and is an array, count() returns the number of elements in the array;
    • if the variable exists but is not an array, the function returns 1;
    • if the variable does not exist, the value 0 is returned.

    array_count_values()

    The array_count_values() function is a variation of sizeof() and count(). Instead of the total number of elements, it counts the number of instances of each value in the array. The syntax of the array_count_values() function is:

    array array_count_values(array array):

    In the returned array, the keys will be the values ​​of the original array, and the values ​​will be their frequencies:

    $states = аrrау("ON", "OK", "SA", "RA", "ON", "ON", "RA", "AK");

    $state_freq = array_count_values($states);

    The $state_freq array is populated with the following associative key/value pairs:

    $state_freq = аrrау("ON" => 3, "OK" => 1, "SA" => 1, "RA" => 2, "AK" => 1);

    Sorting Arrays

    Sorting occupies an important place in programming and is often found in practice in such Internet applications as commercial sites (sorting product categories in alphabetical order, sorting prices) or search engines (sorting programs by the number of downloads). There are nine standard sorting functions in PHP (Table 5.1), and each function sorts an array in a specific way.

    Table 5.1. Sorting functions

    Sorting

    Reverse order

    Storing Key/Value Pairs

    Meaning

    Meaning

    Meaning

    Meaning

    Meaning

    Meaning

    Refers to the use of custom sort functions where the sort order of an array depends on the results returned by the custom function.

    Sorting array elements is not limited to standard criteria, since three functions (usort(), uasort() and uksort()) allow you to set custom criteria and sort information in any way.

    The simplest function sort() sorts the elements of an array in ascending order (from smallest to largest). The syntax of the sort() function is:

    void sort(array array)

    Non-numeric elements are sorted alphabetically according to ASCII codes. The following example demonstrates the use of the sort() function in sorting:

    // Create an array of cities.

    // Sort cities in ascending order

    // Loop through the contents of the array and output all key/value pairs.

    for (reset($cities); $key = key ($cities); next ($cities)):

    print("cities[$key] = $cities[$key]
    ";

    This snippet produces the following output:

    cities = Aprilia

    cities = Nettuno

    cities = Venezia

    As you can see, the $cities array is sorted alphabetically. One variation of this sorting method is implemented in the asort() function described below.

    The rsort() function works exactly the same as the sort() function, with one exception: the array elements are sorted in reverse order. Syntax of the rsort() function:

    void rsort(array array)

    Let's return to the $cities array from the previous example:

    $cities array("Aprilia", "Nettuno", "Roma", "Venezia", ​​"Anzio");

    cities = Venezia

    cities = Nettuno

    cities = Aprilia

    The $cities array is also sorted, but this time in reverse alphabetical order. One variation of this sorting method is implemented in the arsort() function described below.

    The asort() function works much the same as the sort() function mentioned above, however it retains the original association of indexes with elements regardless of the new order of the elements. Syntax of the asort() function:

    void asort(array array)

    Let's return to the $cities array:

    $cities = array("Aprilia", "Nettuno", "Roma", "Venezia", ​​"Anzio");

    As a result of sorting the $cities array using the rsort() function, the elements will be arranged in the following order:

    cities = Aprilia

    cities = Nettuno

    cities = Venezia

    Pay attention to the indices and compare them with those given in the description of the sort() function. This is precisely the difference between the two functions.

    The arsort() function is a variation of asort() that retains the original index association but sorts the elements in reverse order. Syntax of the arsort() function:

    void array(array array)

    Let's use the arsort() function to sort the $cities array:

    $cities = array("Aprilia", "Nettuno", "Roma", "Venezia", ​​"Anzio");

    arsort($cities);

    cities = Venezia

    cities[l] = Nettuno

    cities = Aprilia

    Pay attention to the indices and compare them with those given in the description of the rsort() function. This is precisely the difference between the two functions.

    The ksort() function sorts an array by key, preserving the original key-value associations. Syntax of the ksort() function:

    void ksort(array array)

    For example, consider an array slightly different from the original array

    $wine_producers = array ("America" ​​=> "Napa Valley",

    "Italy" => "Tuscany",

    "Australia" => "Ruthgerlen",

    "France" => "Loire",

    "Chile" => "Rapel Valley");

    As a result of sorting an array using the ksort() function, the elements will be arranged in the following order:

    "America" ​​=> "Napa Valley"

    "Australia" => "Ruthgerlen"

    "Chile" => "Rapel Valley"

    "France" => "Loire"

    "Italy" => "Tuscany"

    Compare the results of sorting $wine_producers with the sort() function:

    "America" ​​=> "Napa Valley"

    "Australia" => "Tuscany"

    "Chile" => "Ruthgerlen"

    "France" => "Loire"

    "Italy" => "Rapel Valley"

    A more than dubious result!

    The krsort() function is almost the same as ksort(), but the keys are sorted in reverse order. Syntax of the krsort() function:

    void krsort(array $array)

    Let's look at sorting the $wi reproducers array using the krsort() function:

    $wine_producers = array ("America" ​​=> "Napa Valley",

    "Italy" => "Tuscany",

    "Australia" => "Ruthgerlen",

    "France" => "Loire".

    "Chile" => "Rapel Valley");

    krsort($wine_producers);

    As a result of sorting, the elements will be arranged in the following order:

    "Italy" => "Tuscany"

    "France" => "Loire"

    "Chile" => "Rapel Valley"

    "Australia" => "Ruthgerlen"

    "America" ​​=> "Napa Valley"

    The sorting functions described above will probably be sufficient for most cases. However, in some situations you may need to define your own sorting criteria. In PHP, this feature is implemented in three standard functions: usort(), uasort() and uksort().

    The usort() function allows you to sort an array based on a criterion defined by the programmer. To do this, usort() is passed the name of the function that determines the sort order as a parameter. The usort() function syntax is:

    void usort (array array, string function_name)

    The array parameter contains the name of the sorted array, and the function_name parameter contains the name of the function on the basis of which the sorting will be performed. Let's say you have a long list of Greek names that you need to memorize for your upcoming history exam. You want to sort the words by length so you start with the longest ones and then learn the short ones when you're tired. To sort an array by length, you can use the usort() function.

    Listing 5.2. Defining sorting criteria for the usort() function

    $vocab = аrrау("Socrates", "Aristophanes", "Plato", "Aeschylus", "Thesmophoriazusae");

    function compare_length($str1, $str2) (

    // Get the length of the next two words

    $length1 = strlen($str1);

    $length2 = strlen($str2);

    // Determine which string has the shorter length

    if ($length1 == $length2) :

    elseif ($length1< $length2) :

    // Call usort() specifying the compare_length() function

    // as sorting criterion

    usort($vocab, "compare_length") :

    // Output sorted list

    while (list ($key, $val) = each ($vocab)) (

    echo "$val
    ";

    In Listing 5.2, the compare_length() function defines how to sort the array. In this case, this is done by comparing the length of the transmitted elements. The criterion function must receive two parameters representing

    array elements to compare. Also notice how these elements are implicitly passed to the criterion function when calling usort(), and how all elements are automatically compared by this function.

    The functions uasort() and uksort() are variants of usort() with the same syntax. The uasort() function sorts an array by user-defined criteria while preserving key/value associations. The uksort() function also sorts the array by custom criteria, but it sorts the keys, not the values.

    Other useful features

    This section describes some functions that do not belong to any specific section, but are undoubtedly useful.

    The arrayjnerge() function merges from 1 to N arrays, combining them according to the order they are listed in the parameters. The array_merge() function syntax is:

    array array_merge(array array1, array array2, ..., array arrayN]

    Let's look at an example of a simple combination of arrays using the arrayjnerge() function;

    $arr_1 = array("strawberry", "grape", "lemon");

    $arr_2 = array("banana", "cocoa", "lime");

    $arr_3 = array("peach", "orange");

    $arr_4 = array_merge ($arr2, $arr_1, $arr_3):

    // $arr_4 = array("banana", "cocoa", "lime", "strawberry", "grape", "lemon", "peach", "orange");

    The array_slice() function returns a slice of an array whose starting and ending positions are specified by the offset from the start and an optional length parameter. The array_slice() function syntax is:

    array array_slice(array array, int offset [, int length])

    • If the offset is positive, the starting position of the returned fragment is counted from the beginning of the array.
    • If the offset is negative, the starting position of the returned fragment is counted from the end of the array.
    • If length is not specified, the returned array includes all elements from the starting position to the end of the array.
    • If a positive length is specified, the returned fragment consists of the specified number of elements.
    • If a negative length is specified, the returned fragment ends within the specified number of elements from the end of the array.

    The array_spl ice() function is vaguely similar to array_slice() -- it replaces a portion of the array, defined by a starting position and an optional length, with elements of an optional array parameter. The array_splice() function syntax is:

    array_splice(array input_array, int offset, , );

    Parameter values ​​are set according to certain rules:

    • If the offset is positive, the starting position of the first element to be removed is counted from the beginning of the array.
    • If the offset is negative, the starting position of the first element to be removed is counted from the end of the array.
    • If length is not specified, all elements from the starting position to the end of the array are removed.
    • If a positive length is specified, the fragment to be deleted consists of the specified number of elements.
    • If a negative length is specified, elements from the array are removed from the starting position to the position that is the specified distance from the end of the array.
    • If replacement_array is not specified, then the elements specified by the offset and optional length are removed from the array.
    • If a replacement_array is specified, it must be enclosed in an array() construct (if it contains more than one element).

    Let's look at a few examples that clearly demonstrate the capabilities of this function. These examples will use the $pasta array (see above) on which various operations will be performed.

    Removing all elements from the fifth position to the end of the array:

    $pasta = array_splice($pasta, 5);

    Removing the fifth and sixth elements:

    $pasta = array_splice($pasta. 5, 2);

    Replacing the fifth and sixth elements with new values:

    $pasta = array_splice($pasta, 5, 2, array("element1", "element2"));

    Removing all elements starting from the fifth until the third element from the end of the array:

    $pasta = array_splice($pasta, 5, -3);

    As you can see from these examples, the array_splice() function provides the flexibility to remove elements from an array with a minimum amount of code.

    The shuffle() function sorts the elements of an array in random order. The shuffle() function syntax is:

    void shuffle(array array);

    Results

    This chapter looked at arrays and standard PHP functions for working with arrays. In particular, the following topics were considered:

    • creating indexed and associative arrays;
    • multidimensional arrays;
    • displaying the contents of multidimensional arrays;
    • element search;
    • adding and removing elements;
    • array size;
    • sorting;
    • other useful features for working with arrays.

    Arrays are very convenient and universal tools for working with data in web applications. In the examples in later chapters, arrays will be used repeatedly to improve the efficiency and clarity of the code.

    In Chapter 6, we'll continue to introduce the basics of PHP. This time we will talk about the object-oriented capabilities of the language.