Unveiling the Potential of PHP Arrays: A Journey into Their Power

Last updated Mar 23, 2024 Published Mar 20, 2018

The content here is under the Attribution 4.0 International (CC BY 4.0) license

Arrays in PHP are very useful, and perhaps the most used resource in programmers’ daily lives. In the not too distant past (from version 4.0 to 5.2), when the Object Orientation Programming (OOP) culture in PHP was not so strong, arrays played the role of the object. It is not very difficult today to visualize legacy systems containing countless arrays.

A good part of this is also due to native PHP functions that return arrays by default, such as functions that search for information in the database, inducing programmers in a certain way. In this chapter, we will demonstrate some of the functions that are most common to PHP applications. But, from now on, we recommend that you browse the language’s official documentation for greater coverage, as PHP has a large number of functions related to arrays.

Associative vs. enumerative arrays

In PHP, we sort arrays depending on their keys, and what we generally learn are arrays with numeric keys:

print [
    0 => 'PHP',
    1 => 'Introduction',
    2 => 'Open Content'
]

This is the typical array we can use. However, PHP is very smart and, with numeric arrays, we don’t need to inform the keys used, as the language already does this for us:

print [
    'PHP',
    'Introduction',
    'Open Content'
]

The first and second example are exactly the same, the only difference is in their syntax. The point we should really pay attention to is how PHP increments array keys. PHP continues to increment its keys based on the largest number in the array, that is, if our last key is 1, in the next element, PHP will create key 2.

$elements = [
    0 => 'PHP',
    1 => 'Introduction'
]

$elements[] = 'Open Content';

In this example, for the Open Content element, the key 2 will be assigned, and so on. An interesting behavior is that we do not necessarily need to follow the ascending order of the keys, we can at any time define a key greater than the previous one:

$elements = [
   0 => 'PHP',
   11 => 'Introduction'
]

$elements[] = 'PHP';

This makes this code completely valid with three elements: in key 0, we have PHP; in key 11, we have the Introduction value; and in key 12 (which was automatically generated), we have the PHP value as well. The dynamism we have with arrays is a very strong feature of PHP.

The story starts to change when we start talking about associative arrays. The big difference between numeric and associative arrays is how we use the keys of each.

With associatives, we can use other data types to form our array. Seeing the following example will make it easier to understand:

$fruits = [
   'melao' => 'yellow',
   'watermelon' => 'red',
   'kiwi' => 'green'
]

Did you notice the difference? Associative arrays can use strings, not just numbers, to identify their elements. Furthermore, with PHP, we have some behaviors that we don’t have in other languages, such as adding an element to an associative array without identifying the key:

$fruits = [
   'melao' => 'yellow',
   'watermelon' => 'red',
   'kiwi' => 'green'
];

$fruits[] = 'orange?';

Before proceeding to the explanation, do you think this excerpt presented is valid? Try to reflect, interpret the code and, after assuming an answer, proceed.

For those who already have some experience with PHP, it’s easy to answer this, and it’s clear that it’s a valid, but confusing, syntax. What will happen here is the creation of a numeric key for the element for which we only specify its value, that is, we will have the keys melao, watermelon, kiwi and 0 (zero).

Array
(
    [melon] => yellow
    [watermelon] => red
    [kiwi] => green
    [0] => orange ?
)

What we should also pay close attention to at this point is that PHP will always use the last numeric key to generate the next key if none is provided. See the following example for a better understanding:

$fruits = [
   'melon' => 'yellow',
   'watermelon' => 'red',
   'kiwi' => 'green'
];

$fruits[10] = 'orange?';

$fruits[] = 'pumpkin';

The result we obtain after running the previous script is an array with the keys melon, watermelon, kiwi, 10 and 11. The explanation is simple: if there is a numeric key, PHP will automatically generate the sequential number of that key; otherwise, key 0 will be assigned (if there is no numeric key), as happened in the first example.

Array
(
    [melon] => yellow
    [watermelon] => red
    [kiwi] => green
    [10] => orange ?
    [11] => pumpkin
)

One last consideration about arrays is the types accepted for identifying keys. PHP has some rules, and one of the first ones that I like to highlight is that it is not possible to use objects and arrays as keys. The second one I like is that floats will be converted to integers.

$books = [
    [] => 'Hello there'
]

This code will result in the following WARNING:

PHP Warning: Illegal offset type in /my_dir/arrays/arrays.php on line 4
PHP stack trace:
PHP 1. {main}() /my_dir/arrays/arrays.php:0

Warning: Illegal offset type in /my_dir/arrays/arrays.php on line 4

Call Stack:
    0.0002 228976 1. {main}() /my_dir/arrays/arrays.php:0

Just like the following code will also cause the same type of error. In PHP, it is not possible to define an object or an array as the key of an element.

$object = new \StdClass();

$arrayInvalid = [];

$arrayInvalid[$object] = 'My value';

As usual, I recommend that you look at the official language documentation about arrays. There you will find examples of contributions from other users and additional information to what I provided.

We can also create multidimensional arrays with PHP in a very simple way. Multidimensional arrays also follow the same rules described so far.

$matrix = [
    'categories' => [
        'subcategory1' => [
            'sub1',
            'sub2',
        ],
        'subcategory2' => [
            'sub1',
            'sub2',
        ]
    ]
];

print_r($array);

We created a multidimensional array in which each category has an array with its respective subcategories. Note that we specify the keys categories, subcategory1 and subcategory2, but we only inform the value for the items in each subcategory, which makes PHP generate the indexes automatically:

Array
(
    [categories] => Array
        (
            [subcategory1] => Array
                (
                    [0] => sub1
                    [1] => sub2
                )

            [subcategory2] => Array
                (
                    [0] => sub1
                    [1] => sub2
                )
        )
)

One point of attention is that PHP manipulates the indices of an array, as Boolean types are converted to integers. Can you tell what the output of the following script will be?

$array = array(
    1 => 'a',
    "1" => 'b',
    1.5 => 'c',
    true => 'd',
);

print_r($array);

Normally, the idea that comes to mind is that PHP will create 4 different positions in the array, each containing the respective keys 1 (integer), 1 (string), 1.5 and true. But, in fact, what really happens is that PHP displays the key 1 with the value d, see:

Array
(
    [1] => d
)

This occurs because PHP has some restrictions on array keys, converting any Boolean type to integer. and rounding float/double types.

Check out other types of restrictions on array keys in PHP in the official documentation, at http://php.net/manual/pt_BR/language.types.array.php.

Organizing data within arrays

From this point on, we will see a series of functions to organize our data within the array, such as: in ascending, descending order, and so on. We will also see some special functions on how to discover an element by its key.

sort

So, let’s go to the first sort function.

$cars = [
    'goal',
    'fiesta',
    'one',
];

sort($cars);

We obtain the following result:

Array
(
    [0] => party
    [1] => goal
    [2] => one
)

By default, the sorting style used by the sort function is SORT_REGULAR (from smallest to largest), which makes the following examples equivalent:

sort($cars);
sort($cars, SORT_REGULAR);

The second thing to note is the use of pass-by-reference of our array - that’s right, the sort function uses this to perform the sorting. It’s good to keep this in mind, as the function will return true in case of success, or will return false if it fails to sort, and not a new sorted array. This is very important to avoid falling into pranks. Given this context, what will be the output of the example below?

$ordering = sort($cars);

print_r($ordering)

When running this script, we get the following result:

1

The $carros array was successfully reordered, however the sort function does not return a new array, but rather a boolean true/false, the famous 1 or 0. For this reason, we see the value 1 , not the sorted array.

$numbers = [
    '29',
    '12',
    '14',
];

sort($numbers, SORT_NUMERIC);

Using the SORT_NUMERIC flag, we force PHP to sort the array numerically, that is, we force PHP to internally compare each element of the array as a numeric type and then sort. See that, in the previous example, we forced numbers as strings, using single quotes, but the function will use the numerical value of each element to sort.

$numbers = [
    '29',
    '12',
    '14',
];

sort($numbers, SORT_STRING);

Just as we can force comparison between elements as numbers, we can do the same thing, but comparing elements as strings. Using the SORT_STRING flag, we force the comparison of the sort function to string, that is, this time our numeric array will be sorted by comparing the values ​​as a string.

$strings = [
    'PHP',
    'ABC',
    'Hello',
];

sort($strings, SORT_LOCALE_STRING);

When working with internationalized applications, sometimes we need to change the application context to another country. For example, let’s say we are writing an application that someone from Russia will use. To do this, we need to change a series of details such as texts, currencies and so on.

PHP provides us with the setlocale function that does exactly this job, and we need to maintain the ordering level according to the locale defined by the user. The SORT_LOCALE_STRING flag does exactly that: it sorts the array according to the application context.

As of PHP 5.4, two new flags were added: SORT_NATURAL and SORT_FLAG_CASE.

$alphabet = [
    'B',
    'z',
    'm',
    'w',
];

sort($alphabet, SORT_NATURAL);

The SORT_NATURAL flag sorts the array alphabetically (from A to Z).

Array
(
    [0] => b
    [1] => c
    [2] => m
    [3] => z
)

It is important to remember that, using the sort function, the array keys are destroyed and new keys are associated with the elements (regardless of whether they are associative or numeric). In our last example, we used a simple array with the elements b, z, m and c, with the respective keys 0, 1, 2 and 3. See that after executing the sort function, the element c (which had the key 3) now has the key 1, and so on with the remaining elements.

For more information about the flags we can use, see the official PHP manual, at http://php.net/manual/pt_BR/function.sort.php#refsect1-function.sort-parameters.

rsort

Now that we know how the sort function works, it will be much easier to understand its derivations (which are not few). The first one we will see here is rsort.

The first thing we must take into consideration is that the rsort function works like sort with its flags. However, as we already know, the sort function orders the elements from the smallest value to the largest (i.e., ascending order), while the rsort function orders its elements from the largest element to the smallest.

$values ​​= [
    1,
    two,
    3,
    4,
];

rsort($values);

See the result we get after running this script:

Array
(
    [0] => 4
    [1] => 3
    [2] => 2
    [3] => 1
)

assort

With the asort function, we have the same behavior that we obtain with the sort function, but with a very important detail: with asort, we maintain the relationship between keys and values ​​in the array.

$fruits = [
   'grape',
   'banana',
   'cashew',
];

asort($fruits);

The result we get after running this script is:

Array
(
    [1] => banana
    [2] => cashew
    [0] => grape
)

Note that the relationship between the keys and the elements remained despite the reordering, and this is exactly the expected behavior for the asort function.

arsort

The arsort function has identical behavior to the rsort function. However, here in the asort function we maintain the relationship between the keys and value of the array elements.

Let’s use the $fruits array as an example, used in the previous example to facilitate understanding and comparison between the different behaviors of the functions:

arsort($fruits);

The result we get after running the script is:

Array
(
    [0] => grape
    [2] => cashew
    [1] => banana
)

Notice how the array keys are maintained. In a normal example with the rsort function, the keys of our array would be in ascending order starting from 0, but as the arsort function maintains the relationship between the keys/values, we obtain the order 0, ` 2 and 1`.

ksort

Another common function we use to sort arrays is the ksort function, which sorts our array by its keys, and not by its values. This type of behavior is very interesting when we are using associative arrays.

$blocks = [
    'A' => 'CASA 81',
    'C' => 'CASA 82',
    'B' => 'CASA 83',
]

ksort($blocks);

See the result we get after running this script:

Array
(
    [A] => HOUSE 81
    [B] => HOUSE 83
    [C] => HOUSE 82
)

Note that the keys were kept and the sorting was performed by the key.

krsort

I believe that, by now, you already have a brief guess as to what the expected behavior of the krsort function is. If you thought that it has the same behavior as the ksort function, except that it sorts from the largest element to the smallest, you are completely correct. That’s exactly what this function does.

Once again, let’s take the previous example to facilitate understanding and comparison between functions:

krsort($blocks);

The result we get after running the script is:

Array
(
    [C] => HOUSE 82
    [B] => HOUSE 83
    [A] => HOUSE 81
)

Again, we must pay attention when passing the array to the ksort function, as it receives the array as a reference and returns true when successfully sorting the array; or returns false if it fails.

user

Through the sea of ​​deductions that PHP offers us, the U of the usort function gives us a small hint of what awaits us. Yes, using usort we can define a sort function and use it to sort the array (U for user).

usert($folders, function($a, $b) {
  return ($a > $b) ? -1 : 1;
});

Note that this function receives the array as a reference, and returns true or false.

natsort

We use natsort to sort our array in a natural way that humans are used to seeing, that is, in alphabetical order. If you are wondering until now why we have natsort if the sort family functions already sort in an “alphabetical” way, you are wrong. There is a difference between the algorithms applied in both functions. We should emphasize that the functions of the sort family are ordered from smallest to largest or from largest to smallest, whereas natsort is ordered in a natural way for humans.

Let’s use a simple comparison between the sort and natsort functions. See our example for the images to be sorted:

$images = [
    'img12.png',
    'img10.png',
    'img2.png',
    'img1.png'
];

sort($images);

print_r($images);

And the result we get is the following:

Array
(
    [0] => img1.png
    [1] => img10.png
    [2] => img12.png
    [3] => img2.png
)

Notice how order is not in a natural form for us human beings. When ordering the images, we would expect something more like: img1.png, img2.png, img10.png and img12.png. To obtain this result, we use the natsort function.

natsort($images);

print_r($images);

And the result we get this time is as expected:

Array
(
    [3] => img1.png
    [2] => img2.png
    [1] => img10.png
    [0] => img12.png
)

An easier approach to the sort functions

After all these functions, I believe your head is full of new features and excited about the new things you learned. But, before we move on to the next topic about arrays, I would like to leave here a tip that helped me a lot during my studies.

Note that functions that maintain relationships between keys always start with A, such as asort and arsort. Try to associate that, when using one of the functions that start with the letter A, the keys will always be maintained.

And just like the letter A, we have the letter R, like rsort, arsort, krsort, which are related to the opposite order. In other words, the function without R will order from smallest to largest, and the function that contains R will order from largest to smallest.

Lyrics Option
A Associative - Associative, generally used to maintain array keys
K Key - Used to sort the array by its key, not by value
U User - It is possible to define a function to sort the array
R Reverse - The letter R is associated with a function that already exists, for example, the ksort function, which sorts the array in ascending order, and the krsort function, which sorts the array by key, but in descending order (i.e. the reverse of the ksort function)

Adding and removing elements

In PHP, we have some functions that allow us to add and remove elements. The first one we will look at is the array_push function, which allows us to add one or more elements to the end of our array.

$electronics = [];

array_push($eletronicos, 'videogame', 'tv', 'dvd');

After executing the code, we have an array with three elements. An important feature of this function is that it accepts any type of data to be added to the array:

$electronics = [
    'radio'
];


array_push($eletronicos, ['videogame', 'tv', 'dvd'], [], 123, 456, new \StdClass());

The result we get after running this script is:

Array
(
    [0] => radio
    [1] => Array
        (
            [0] => video game
            [1] => tv
            [2] => dvd
        )

    [2] => Array
        (
        )

    [3] => 123
    [4] => 456
    [5] => stdClass Object
        (
        )

)

Once again, we need to be careful about using functions that use passing as a reference. Note that the array_push function receives the array as a reference, and the return value of the function is the total number of the array after adding the new elements.

The array_push function adds one or more elements to the end of the array, but what if we want to add 1 or more elements to the beginning? To do this, we use the array_unshift function.

$home = [
    'window'
];

array_unshift($home, ['rooms'], 'door');

The result we get after running the script is:

Array
(
    [0] => Array
        (
            [0] => rooms
        )

    [1] => port
    [2] => window
)

Now that we know how to add elements, we need to know how to remove them. To remove elements in arrays, we can use the array_pop and array_shift functions.

As in the array_push function, in which we add the element to its end, we use the array_pop function to remove the last element from the array. See the following example where we consider the array used in the previous example. Let’s remove the window element, which is the last one.

array_pop($house);

When we run the script, we get the following result:

Array
(
    [0] => Array
        (
            [0] => rooms
        )

    [1] => port
)

Now, to remove an element at the beginning of the array, we use the array_shift function. See that now, in our $house array, we only have two elements left: an array and a string. We will use the array_shift function to remove the first element so that we are left with just the door element.

array_shift($house);

print_r($house);

When we run this script, we get the following result:

Array
(
    [0] => port
)

array_walk

PHP provides us with a very interesting function to apply a callback to each element of the array:

$versions = [
    'PHP 5.2',
    'PHP 5.3',
    'PHP 5.4'
];

array_walk($versions, function ($item) {
    printf('%s', $item);
});

This example of ours just displays the PHP versions in our $versions array.

PHP 5.2
PHP 5.3
PHP 5.4

Additionally, we can get the array keys by also passing a second parameter to our callback.

$versions = [
    'PHP 5.2',
    'PHP 5.3',
    'PHP 5.4'
];

array_walk($versions, function ($item, $key) {
    printf('%d => %s', $key, $item);
});

Now, for each element traversed, in addition to displaying its value, we also display the corresponding key.

0 => PHP 5.2
1 => PHP 5.3
2 => PHP 5.4

If it is necessary to pass any type of extra data to the callback, simply enter it as the third parameter of the array_walk function, and of the callback as well.

$versions = [
    'PHP 5.2',
    'PHP 5.3',
    'PHP 5.4',
];

$releasedate = [
    '02/01/1990',
    '02/05/2000',
    '03/06/2020',
];

array_walk($versions, function ($item, $key, $Extradata) {
    printf('%d => %s release date: %s', $key, $item, $dadosExtras[$key]);
}, $Launchdate);

What we did was simply pass an array $dataDeLancamento with the same keys as the array $versoes so that it was possible to display the release date of each version of PHP from within the callback function.

0 => PHP 5.2 release date: 02/01/1990
1 => PHP 5.3 release date: 02/05/2000
2 => PHP 5.4 release date: 06/03/2020

In addition to using the parameters of the array_walk function itself, we can also use the maximum that closures provide us.

$total = 0;

$versions = [
    ...
];

array_walk($versions, function ($item, $key) use (&$total) {
    $total++;
});

print $total;

In this type of use of the array_walk function, instead of using the third parameter to inject extra data into the callback function, we use the callback itself for this, generating the total number of times the callback was executed:

3

Joining and comparing arrays

PHP provides us with the array_merge function that allows us to merge one or more arrays. This function returns a new array with the joined elements. Unlike the sort functions we’ve seen so far, array_merge works by passing parameters by value, not by reference:

$animals = [];

$uniao = array_merge($animais, ['cat'], ['dog']);

print_r($uniao);

The union of the two arrays will return a new array with two elements:

Array
(
    [0] => cat
    [1] => dog
)

Let’s go to the main rules:

  1. Elements with the same value are not overwritten, they are just added to the end of the array:

     $animals = [];
    
     $uniao = array_merge($animais, ['cat'], ['dog'], ['dog']);
    
     print_r($uniao);
    

    Result:

     Array
     (
         [0] => cat
         [1] => dog
         [2] => dog
     )
    
  2. Elements with the same associative key (string keys are overwritten, numeric keys are not) are overwritten and the value of the last element is what will prevail:

     $animals = [];
    
     $uniao = array_merge($animals, ['cat'], ['c' => 'big dog'], ['c' => 'dog']);
    
     print_r($uniao);
    

    Result:

     Array
     (
         [0] => cat
         [c] => dog
     )
    
    1. Numeric array keys will be reordered:
     $mvc = [
         0 => 'laravel',
         1 => 'silex',
         2 => 'symfony'
     ];
    
     $orm = [
         0 => 'doctrine',
         1 => 'eloquent'
     ];
    
     $reordenarChaves = array_merge($mvc, $orm);
    

Note that, when joining the arrays, the keys are reordered:

Array
(
    [0] => laravel
    [1] => silex
    [2] => symfony
    [3] => doctrine
    [4] => eloquent
)

This occurs regardless of whether we have associative keys mixed in the array. See in our next example that the numeric keys are reordered, but the associative ones prevail:

$mvc = [
    'l' => 'laravel',
    1 => 'silex',
    2 => 'symfony'
];

$orm = [
    'd' => 'doctrine',
    1 => 'eloquent'
];

Notice the result we obtain, and the numeric keys being reordered and the associative ones being maintained:

Array
(
    [l] => laravel
    [0] => silex
    [1] => symfony
    [d] => doctrine
    [2] => eloquent
)

In addition to joining arrays, we can compare them. To achieve this, PHP provides us with a series of functions to facilitate this type of task. The first function we will see here is array_diff. With it, we can calculate the difference between array A and array B, C, D and so on.

The return of this function is very simple: it will return all the elements that are in array A, but are not present in the others.

$a = [
    'stone',
    'paper',
];

$b = [
    'scissors',
];

$difference = array_diff($a, $b);

print_r($difference);

The result is:

Array
(
    [0] => stone
    [1] => paper
)

The array_diff function uses only the values ​​of an array as comparison, not taking into account its keys. To do this, we have the function array_diff_assoc, which will perform the comparison including the keys of an array:

$a = [
    'p' => 'stone',
    'paper',
];

$b = [
    'scissors',
    'stone',
];

$difference = array_diff_assoc($a, $b);

print $difference;

The result is:

Array
(
    [p] => stone
    [0] => paper
)

As we can see, we have the value pedra in both arrays, but the keys are different, which means the array_diff_assoc function cannot recognize the two as equal. This is because, in the array $a, the key of the value pedra is p, and in the array $b the value is 1:

$a = ['p' => 'stone'];
$b = [1 => 'stone'];

Remember that both the key and the value are used to compare, so they must both be the same.

And since we’re talking about keys, we can also differentiate arrays just by their keys, with the array_diff_keys function:

$a = ['a' => 'rice', 'f' => 'beans'];

$b = ['c' => 'shrimp', 'z' => 'rice'];

$difference = array_diff_keys($a, $b);

print_r($difference);

The result is:

Array
(
    [a] => rice
    [f] => beans
)

As we can see, we have an element with the same value rice, but its keys are different. If comparison by key and value (or key and value) does not satisfy your needs, PHP provides a function so that you can enter a function by which we want to differentiate the arrays, array_diff_uassoc. It operates exactly like the array_diff_assoc function, but we can define our function to perform the key comparison.

$a = [
    1,
    two,
    'a' => 'car',
];

$b = [
    'a' => 'car',
    3,
    5,
];

$difference = array_diff_uassoc($a, $b, function($a, $b) {
    return 0;
});

print_r($difference);

See how interesting: we can modify the behavior when checking the array keys. In our case, despite having two equal elements, including their keys (a => car), the function returns us that there are no elements from the array $a in the array $b:

Array
(
    [0] => 1
    [1] => 2
    [a] => car
)

Try changing the function to return other values, remove the parameters and see what happens. What will happen if we remove the function passed as a third parameter?

And of course we have the same function, however, to compare by array keys, we can define a function, array_diff_ukey.

$a = [
    'b' => 1,
    'a' => 'car',
    'c' => 3,
];

$b = [
    'c' => 'car',
    'a' => 'nothing',
    5,
];

$difference = array_diff_ukey($a, $b, function($a_key, $b_key) {
    if ($a_chave === $b_chave) {
        return 0;
    } else if ($a_chave > $b_chave) {
        return 1;
    } else {
        return -1;
    }
});

print_r($difference);

With the function passed as third parameters, we obtain the same behavior as the array_diff_key function (do you remember what it does?), and we return the keys that exist in the array $a, but are not in the other arrays (in ours case, the array $b).

Array
(
    [b] => 1
)

Checking the value of an array

Normally, we are used to using the empty or isset functions to check if there are elements inside an array or if it is empty.

$empty = [];

if (empty($empty)) {
    print 'It's empty';
}

We can also achieve the same result with the isset function.

$empty = [];

if (isset($empty)) {
    print 'It's empty';
}

When running these examples, both will display the message: It is empty. However, in the scenario shown in the previous example, we can only check whether a value within a given key exists. But what if we need to check if a particular array key exists instead of its value? Using the isset/empty functions becomes impossible, so we use the array_key_exists function:

$computer = [];

if (array_key_exists('componentes', '$computer')) {
    print 'The key "components" exits !';
}

This gives us the opportunity to check if a key exists, even if it has no value.

$computer = [
    'components' => null
];

if (array_key_exists('componentes', '$computer)) {
    print 'The key "components" exits !';
}

Generators

In version 5.5 of PHP, a new functionality was introduced into the language. In other languages ​​(Python, for example), the concept of generators was already well known and used, and now we have the opportunity to use generators in PHP through the reserved word yield.

function myGenerator()
{
    for ($i = 0; $i < 10; $i++) {
        yield $i;
    }
}

How can we use this generator? Very simple: we can iterate over it, thanks to the Generator class (http://www.php.net/manual/en/class.generator.php). See our example:

foreach (myGenerator() as $number) {
    print $number;
}

And the result we get is:

0 1 2 3 4 5 6 7 8 9

Did you notice we don’t use return? Well, it seems a little strange, but it’s not that strange. Instead of returning the value only when we have all the values, with yield we produce the value on demand. And in a real context, where could we use this? Reading the contents of a file would be a good case:

function filelines($file) {
    $file = fopen($file, 'r');
    
    while (($fileline = fgets($file)) !== false) {
        yield $fileline;
    }
    
    fclose($file);
}

As in our previous example, just iterate over the Filelines to get the content:

foreach (filelines('text.txt') as $fileline) {
    ...
}

list

When manipulating arrays in PHP, it is very common to iterate using a for loop:

$chocolate = [
    'white',
    '500g',
    'R$ 5.50'
];

for ($i = 0; $i < count($chocolate); $i++) {
    print $chocolate[i];
}

With this, we obtain the values ​​of each position in our array:

white
500g
R$ 5.50

However, this is not a very easy way to understand what is in each position, is it? In PHP, we have a function that helps us make the code more readable:

list($type, $size, $price) = $chocolate;

Using list, we can enumerate the array elements in a variable, making it possible to create names that mean something to us while we are writing the code:

list($type, $size, $price) = $chocolate;
    
print $type . $size . $price;

With this code, we will obtain the same result when using the for loop as in the previous example.

white
500g
R$ 5.50

As in our example we only have a few elements, it may not be very clear how interesting this type of use is. Let’s look at a slightly more complicated example with a slightly more complex array:

$computers = [
    ['2GB', '80GB', 'duo core'],
    ['6GB', '120GB', 'core i5'],
    ['4GB', '500GB', 'core i7'],
    ['4GB', '500GB', 'core i7'],
];

Our array has 4 elements, which are also arrays:

Array
(
    [0] => Array
        (
            [0] => 2GB
            [1] => 80GB
            [2] => duo core
        )
    [1] => Array
        (
            [0] => 6GB
            [1] => 120GB
            [2] => core i5
        )
    [2] => Array
        (
            [0] => 4GB
            [1] => 500GB
            [2] => core i7
        )
    [3] => Array
        (
            [0] => 4GB
            [1] => 500GB
            [2] => core i7
        )
)

Let’s see how we would do it in a traditional way to display the elements:

for ($i = 0; $i < count($computers); $i++) {
    for ($c = 0; $c < count($computers[$i]); $c++) {
        print $computers[$i][$c];
    }
}

Basically, we have a row and column structure in our $computers array, which makes us use two repetition loops, one for the row and one for the columns, and thus we obtain the desired result:

2GB 80GB dual core
6GB 120GB core i5
4GB 500GB core i7
4GB 500GB core i7

With two repetition loops, the code is a little more difficult to understand. So let’s use list to help us in this case.

for ($i = 0; $i < count($computers); $i++) {
    list($memory, $hd, $processor) = $computers[$i];
    
    print $memory . $hd . $processor;
}

This way, we obtain the same result, but the difference between the two is clear. Using list is by far a much more elegant and easier to understand way:

2GB 80GB dual core
6GB 120GB core i5
4GB 500GB core i7
4GB 500GB core i7

Resources