PHP offers a bunch of useful functions to operate with arrays. With some clever combination, we can easily create nice and very handy functionality. Let’s check some.
Set Values But Keep Keys
In some cases, we want to keep the array keys but set all the values for example to null. We can do it with foreach() or array_map(), but there is a nice one-liner as well.
$array = ['name' => 'Pine', 'code' => '1128852', 'location' => 'Hungary']; $new = array_fill_keys(array_keys($array), null); // ['name' => null, 'code' => null, 'location' => null]
Combining these two functions we can reproduce an array with the same keys, however, all the values are set to null.
“Map” to an Associative Array
Another scenario, when we have an array and we want to create another array, where one of the items is the key and another is the value of the new array.
$array = [['id' => 'id_1', 'name' => 'Jon'], ['id' => 'id_2', 'name' => 'Jane']]; $new = array_column($array, 'name', 'id'); // ['id_1' => 'Jon', 'id_2' => 'Jane']
The array_column() function is a very handy yet powerful feature, however, it’s not well known. In many cases, it can be a nice replacement for a Laravel Collection’s mapWithKeys() method.
Divide Keys and Values
Let’s say we have an associative array, but for some reason, we want to divide it into two arrays. One that contains the keys and another one for the values.
$array = ['id' => 1, 'name' => 'Jane', 'age' => 30]; $new = [array_keys($array), array_values($array)]; // [['id', 'name', 'age'], [1, 'Jane', 30]]
Get Only the Given Keys of the Array
It’s possible, we have a bigger array, but we want to use just a piece of it, some values with the specified keys.
$array = ['id' => 1, 'name' => 'Jane', 'age' => 30, 'location' => 'Bp']; $new = array_intersect_key($array, array_flip(['id', 'age'])); // ['id' => 1, 'age' => 30]
Modifying and Filtering Values
What if we have a set of words, that can contain spaces as well. We want to trim the words and keep only the array items that are containing “real” characters.
$array = ['He ', 'loved', ' ', ' us ', 'first ']; $new = array_filter(array_map('trim', $array)); // ['He', 'loved', 'us', 'first']
As we can see, there are plenty of handy variations, which is good news, because our project can have a special need, yet we can bring something simple and elegant solution.
PHP arrays have an important role in application development, so it’s important to know how to use them.
Need a web developer? Maybe we can help, get in touch!