DEV Community

spO0q πŸ’
spO0q πŸ’

Posted on • Edited on

Things you probably don't know about PHP arrays

Everybody uses arrays whether it's Php or not. Regarding Php arrays there are special functions you can use to make the most of them.

Arrays are easy to use and quite efficient.

What you probably already know

Arrays are data structures. This is what it looks like :

$alphabet  = ["a", "b", "c"];
$_alphabet = range("a", "c");
Enter fullscreen mode Exit fullscreen mode

It creates lists. Far far better than :

$a = "a";
$b = "b";
$c = "c";
... etc
Enter fullscreen mode Exit fullscreen mode

And when dealing with specific values we can easily access them e.g :

$a  = $alphabet[0];
$_a = reset($_alphabet);// it's just another way to get "a"
Enter fullscreen mode Exit fullscreen mode

There are different types of arrays, some of them can have complex structure because specific keys can be defined as strings. You can even create multiple nested levels.

Php deeply

There are related terms for arrays :

  • lists
  • dictionaries
  • collections
  • trees

source

Php stores these structures in let's say "slots". Under the hood (internally) there is a hash function that computes data with integers in these slots.

Besides data are added in a way that Php remembers the exact ascending order they were added.

If you want to know how it's done you have to go deeper.

Ordered lists of elements

Simple arrays do not have named keys, if you want to access a particular value you can do the following :

$alphabet  = ["a", "b", "c"];
$a         = $alphabet[0];
Enter fullscreen mode Exit fullscreen mode

In this case it works because obviously I have only 3 elements in that list so who cares... but in real life arrays can contain hundreds, thousands of entries. So that would be very lame this way.

Fortunately arrays can contain key/value pairs with named keys and when you specify names for your keys (as strings) the storing part is quite different.

Going a little bit deeper with hash tables

Ok we just saw data are stored in slots but that's still kind of abstract.

Arrays are actually implemented with hash tables. It's how Php indexes memory, it's how the internal hash function computes data with integers in slots.

When you use named keys (associative array), it's first converted to integers before indexing memory. The index stored as integer in memory contains the key/value pairs.

When you do this, you create maps.

source

Hash tables are used to store pretty much everything such as functions, methods, objects, arrays, variables.

C - origins

Php is implemented with C. The hash function computes your keys with integers. These integers are offsets in C arrays which contain linked list of possible values. Php runs all these possible values until it finds the matching element.

You don't have to specify key if it's an integer

Non-associative arrays do no need to be written like that :

$actresses = [ 0 => 'Scarlett Johansson', 1 => 'Ann Hathaway', 2 => 'Charlize Theron' ];
Enter fullscreen mode Exit fullscreen mode

instead just write :

$actresses = [ 'Scarlett Johansson', 'Ann Hathaway', 'Charlize Theron' ];
Enter fullscreen mode Exit fullscreen mode

Php automatically increments keys as integers starting at 0.

Array Destructuring

You can do the following :

$actresses = [
    [ 'Scarlett Johansson', 'Lost in Translation' ],
    [ 'Ann Hathaway', 'Interstellar' ],
    [ 'Charlize Theron', 'Aeon Flux' ],
];

foreach ($actresses as $actress) {
    [ $person, $movie ] = $actress;
    echo "$person in $movie" . PHP_EOL;
}
Enter fullscreen mode Exit fullscreen mode

Here [ $person, $movie ] = $actress;is the shorthand for list($person, $movie) = $actress;

In this example if you just want movies without actresses indeed do not use $person and add a comma before $movie :

foreach ($actresses as $actress) {
    [ ,$movie ] = $actress;
    echo "$movie" . PHP_EOL;
}
Enter fullscreen mode Exit fullscreen mode

Cut arrays in chunks

Php has a less known function called array_chunk() which can divide your array into equal parts :


$actresses = [
    [ 'Scarlett Johansson', 'Lost in Translation' ],
    [ 'Ann Hathaway', 'Interstellar' ],
    [ 'Charlize Theron', 'Aeon Flux' ],
];

print_r(array_chunk($actresses, 3));
Enter fullscreen mode Exit fullscreen mode

will display :

Array
(
    [0] => Array
        (
            [0] => Array
                (
                    [0] => Scarlett Johansson
                    [1] => Lost in Translation
                )

            [1] => Array
                (
                    [0] => Ann Hathaway
                    [1] => Interstellar
                )

            [2] => Array
                (
                    [0] => Charlize Theron
                    [1] => Aeon Flux
                )

        )

)

Enter fullscreen mode Exit fullscreen mode

Wrap up

Php arrays are very powerful and fun. You have to go a little bit deeper to understand how it's stored in memory. I hope this introduction encourages you to read more about it.

Top comments (5)

Collapse
 
moopet profile image
Ben Sinclair

Your demonstration of array_chunk is a little confusing as it doesn't result in anything other than the original array wrapped in another. Could I suggest demoing with a size parameter of 2, which would split the array into two chunks of lengths 2 and 1, and make it a bit clearer what's going on?

Collapse
 
suckup_de profile image
Lars Moelleken

If someone want to see how far you can go with php array functions, please take a look at "Arrayy" :) β‡Ύ github.com/voku/Arrayy

e.g.

\Arrayy\Type\StringCollection::create(['Array', 'Array'])->unique()->append('y')->implode() // Arrayy

Collapse
 
hbgl profile image
hbgl • Edited

Arrays are actually implemented with hash tables.

Internally, PHP has the notion of packed arrays. These are arrays that have consecutive integer indices, e.g. ['foo', 'bar', 'baz'], with some additional caveats. The interesting thing is, that they are not implemented with a hash table, but with a contiguous list. I thought this would be interesting to know because it can give you a performance boost in some applications.

Collapse
 
leob profile image
leob

Didn't know about array destructuring, cool!

Collapse
 
damlight profile image
Daei_F

Neither I did, though I'm pretty new to PHP, even then it's good to know these useful things