PHP crash course : Array manipulation
Tags: php, backends, tutorial, beginners
Published: 2022-01-17 13:42:59

---
title: PHP crash course : Array manipulation
published: true
description: 
tags: php, backends, tutorial, beginners
cover_image: https://dev-to-uploads.s3.amazonaws.com/uploads/articles/8dcf1kf25snri1hxs7ma.jpg
series: ModernPHP
---
Today you will learn array création and manipulation in PHP.

This PHP crash course is free and will be posted here on dev.to. I'll be releasing a new article/post every two days or so. To not miss anything, you can follow me on twitter: <a href="https://twitter.com/EricTheCoder_" class="twitter-follow-button" data-show-count="false">Follow @EricTheCoder_</a><script async src="https://platform.twitter.com/widgets.js" charset="utf-8"></script>

First, here is a very common scenario in web development that will help you to understand why we need Array.

In the next exemple, we need to display a list of products and their prices.
```php
$product1 = "iPad";
$product2 = "iPhone";
$product3 = "iWatch";

$price1 = 599;
$price2 = 899;
$price3 = 699;

echo $product1 . ' : ' . $price1 . '<br>';
echo $product2 . ' : ' . $price2 . '<br>';
echo $product3 . ' : ' . $price3 . '<br>';
```

As you can imagine, this code is far from optimal. Imagine if we had 100 products or even 10,000 products.

There is a way to do the previous exemple in a much more efficient way... Arrays.

Arrays in PHP are a lists of values. Values in an array can be of different type.

To define an array we use square brackets [ ]
```php
$products = [];
```
The variable $products is an array

It is possible to create an array with content
```php
$products = ['iPad', 'iPhone', 'iWatch'];
```
This array contains three strings: iPad, iPhone, iWatch

Each array element is separated by a comma.

It is possible to have arrays with different type of variable
```php
$array = ['First entry', 100, true];
```

It is even possible to create an array within an array
```php
$array = ['First entry', 100, ['iPad', 'iPhone'], false];
```

### To access an item
```php
echo $array[0];
// First entry
```
The elements of an array are indexed from 0. So the first item is at position 0, the second at position 1, and so on.
```php
$array = ['First entry', 100, ['iPad', 'iPhone'], false];
                 0         1           2            3
```
To access an array within an array you use the following syntax
```php
echo $array[2][1];
// iPhone
```
Here we display element 2, i.e. [&#39;iPad&#39;, &#39;iPhone&#39;]
Then element 1 is iPhone

If you attempt to access a non-existent item. PHP will return a warning and the value null.
```php
$array = ['First entry', 100, true];

echo $array[3];
// null 
// Warning: Undefined array key 3
```

### Count
To determine the number of items in an array you can use the count() function
```php
$array = ['First entry', 100, true];

echo count($array);
// 3
```

### Array manipulation
Add an element at the end of the array
```php
$array[] = 'Last';

// ['First entry', 100, ['iPad', 'iPhone'], false, 'Last']
```

Remove an element from the array
```php
unset($array[0]);

// [100, ['iPad', 'iPhone'], false, 'Last']
```

Convert an array to a string with the implode function
```php
$array = ['One', 'Two', 'Three'];
echo implode(', ', $array);
// "One, Two, Three"
```
The first parameter is the separator.

Transform a string into an array with the explode function
```php
$text = 'Mike, Shawn, John';
echo explode(',', $text); // ['Mike', 'Shawn', 'John'];
```
The first parameter is the separator.

### Iterate through all elements of an array
The foreach function executes code for each element of the array.
```php
$names = ['Mike', 'Shawn', 'John'];

foreach($names as $name) { 
   echo 'Hello ' . $name;
}
```
The first parameter is the name of the array to browse, the second parameter represents the reference to the current element.

### Associative arrays
So far we have learned how arrays work. They have a number key starting from 0.

It is possible to create arrays with a custom key. This is what PHP calls associative arrays.
```php
$person = ['age' => 45, 'genre' => 'men'];
```
Here &#39;age&#39; and &#39;gender&#39; are the keys. 45 and men are the values associated with these keys.
Note that some programming languages call this type of array a dictionary.
Associative arrays are very practical and you must understand them well because you will use them very often. They are perfect for storing information.
```php
$product = ['id' => 100, 'name' => 'iPad', 'price' => 699];
```

Access to an array value is done with the key
```php
echo "Product :" . $product['name'];
```

Adding a key/value to the array is possible by specifying a new key
```php
$product['qty'] = 5;
```

It is possible to check if a key exists
```php
$product = ['id' => 100, 'name' => 'iPad', 'price' => 699];

echo array_key_exists('id', $product);
// true
```

### Loop in an associative array with values and keys
```php
foreach($names as $key => $value) {
   echo $key . ' : ' . $value;
}
```

### Concatenation: Join two arrays
```php
$names1 = ['Mike', 'Paul', 'Tom'];
$names2 = ['John', 'Sam'];

$allNames = array_merge($names1, $names2);
// ['Mike', 'Paul', 'Tom', 'John', 'Sam'];
```

Concatenation with the spread operator (...)
```php
$names1 = ['Mike', 'Paul', 'Tom'];
$names2 = ['John', 'Sam'];

$allNames = [...$names1, ...$names2];
// ['Mike', 'Paul', 'Tom', 'John', 'Sam'];
```

Here, the spread operator before the array name (...$names) deconstructs the array.
### An array of associative arrays
A pattern that you will use often is an array containing associative arrays.
```php
$items = [
    ['id' => '100', 'name' => 'product 1'],
    ['id' => '200', 'name' => 'product 2'],
    ['id' => '300', 'name' => 'product 3'],
    ['id' => '400', 'name' => 'product 4'],
];
```

This kind of table is excellent for representing data.
It is possible to loop and display each item
```php
foreach($items as $item) {
    echo $item['name'] . <br>;
}
```
The 'as' statement create a reference to the array item. 

### Retrieve part of an array
There are several functions that allow you to retrieve part of an array.
Retrieve only keys or values
```php
$person = ['age' => 45, 'genre' => 'men'];

// Return an array with only keys
echo array_keys($person); // ['age', 'genre']

// Return an array with only values
echo array_values($person); // [45, 'men']
```

Retrieval of items that match a specific criterion with the array_filter() function
```php
$items = [
    ['id' => 100, 'name' => 'product 1'],
    ['id' => 200, 'name' => 'product 2'],
    ['id' => 300, 'name' => 'product 3'],
    ['id' => 400, 'name' => 'product 4'],
];

$filteredItem = array_filter($items, function ($product) {
    return $product['id'] > 200;
});

print_r($filteredItem);
// $items = [
//    ['id' => '300', 'name' => 'product 3'],
//    ['id' => '400', 'name' => 'product 4'],
// ];
```

The array_filter() function is a function with a callback function as parameter. For each item in the array an expression will be evaluated. If the expression is true, the current item will be included in the resulting array.

### Search in an array
```php
$items = [
  ['id' => '100', 'name' => 'product 1'],
  ['id' => '200', 'name' => 'product 2'],
  ['id' => '300', 'name' => 'product 3'],
  ['id' => '400', 'name' => 'product 4'],
];

$found_key = array_search('product 3', array_column($items, 'name'));
// 2
```
The array_search() function allows you to search for a specific key according to a search criterion. In the last example we look for the key of &#39;product 3&#39; in the &#39;name&#39; column

### Create a new array with the array_map() function
```php
$items = [
    ['id' => 100, 'name' => 'product 1'],
    ['id' => 200, 'name' => 'product 2'],
    ['id' => 300, 'name' => 'product 3'],
    ['id' => 400, 'name' => 'product 4'],
];

$mapItems = array_map(function ($product) {
    return [
        'id' => $product['id'] * 2, 
        'name' => $product['name']
    ];
}, $items);

print_r($mapItems);
//[
    ['id' => 200, 'name' => 'product 1'],
    ['id' => 400, 'name' => 'product 2'],
    ['id' => 600, 'name' => 'product 3'],
    ['id' => 800, 'name' => 'product 4'],
];
```
The array_map() function returns an array that contains what each callback item will return.

The array_map() function must have two parameters: a callback function and an array. ex. array_map(callback function, arrays)

The array_map() function loops over each array item and at the same time builds a new array. Each item in the new array is the result (return) of the callback function. In the last example, each loop returned an item with the id * 2 and the product name.

The original table is not modified, a new table is created.

### The array_reduce() function
This function takes an array and reduces it to a single value. Eg returned the result of adding all numbers contains in an array.
```php
$numbers = [2, 4, 6, 100];

$sum = array_reduce($numbers, function ($num, $total) {
    return $total + $num;
}, 0);

print_r($sum);
// 112
```
The array_reduce() function take two parameters: reference to actual item and a total variable. For each iteration, the callback function return the result in the total variable.

## Conclusion
That's it for today, I'll be releasing a new article every two days or so. To be sure not to miss anything you can follow me on twitter: <a href="https://twitter.com/EricTheCoder_" class="twitter-follow-button" data-show-count="false">Follow @EricTheCoder_</a><script async src="https://platform.twitter.com/widgets.js" charset="utf-8"></script>