10 PHP Array Functions And How To Use Them
Tags: php, array
Published: 2023-03-04 11:27:42

# `in_array()`


This array method checks if a value is in a given array. 
It accepts 3 arguments:

 - The value we want to search for in an array.
 - The array from which we want to search for the value.
 - An optional third boolean argument. If this value is provided, `in_array()` will check if the type of the value and its equivalent in the array are the same.

    It returns a `boolean`, that is, `true` or `false` depending on if the value is found in the array or not.

```php
$companies = ['facebook', 'twitter', 'google', 'apple'];
in_array('facebook', $companies);
//true
in_array('amazon', $companies);
//false

$numbers = [1, '2', 3, 4, 5, 6];
in_array(1, $numbers);
//true
in_array(2, $numbers, true);
//false
```

We can also search for an array in an array using this function.

```php
$colors = [['green', 'blue'], ['red', 'yellow'], 'black'];

if (in_array(['green', 'blue'], $colors)) {
    echo "found!";
}
//found!
```



# `array_push()`

It adds one or more new items at the end of an array and increases the length of the array by the number of new items added.

It takes in two arguments:

 - The input array.
 - The list of items to be added to the array.

```php
$friends = ['Alice', 'Bob', 'Charlie'];

array_push($friends, 'Dave');

print_r($friends);
// ['Alice', 'Bob', 'Charlie', 'Dave']

$fruits = ['apple', 'banana', 'orange'];

array_push($fruits, 'kiwi', 'mango', 'Grapefruit');

print_r($fruits);
//['apple', 'banana', 'orange', 'kiwi', 'mango', 'Grapefruit']
```

`array_push()` does the same thing as adding to the array using the shorthand syntax:

```php
$friends = ['Alice', 'Bob', 'Charlie'];

$friends[] = 'Danny';

print_r($friends);

//['Alice', 'Bob', 'Charlie', 'Danny']
```



# `array_pop()`

It removes from the end of an array and returns the removed array item.

It decreases the length of the array by 1 at a time.

It takes only one argument, the array to modify.

```php

$birds = ['sparrow', 'crow', 'pigeon'];

$last_bird = array_pop($birds);

print_r($birds);
//['sparrow', 'crow']

echo "Removed bird: " . $last_bird;
//Removed bird: pigeon
```

# `array_keys()`

It takes in an array and returns all or some of the keys in a numerically indexed array.

It accepts three arguments:

-   The input array.
-   An optional filter value that specifies how many keys of the array should be returned. If it is not provided, all the keys will be returned.

-   An optional third boolean argument, the default is false. If this value is provided, `array_keys()` will check if the type of the value and its equivalent in the array are the same.

 ```php
$countries = [
    'USA' => 'United States',
    'CAN' => 'Canada',
    'MEX' => 'Mexico',
    'BRA' => 'Brazil',
    'ARG' => 'Argentina'
];

$codes = array_keys($countries);

print_r($codes);
//['USA', 'CAN', 'MEX', 'BRA', 'ARG']
```

To return the `USA` key only, we will add a second argument in the `array_keys()` method.

The second argument can be a value of any type, such as a string, number, or boolean. However, it cannot be a function.

```php
$countries = [
    'USA' => 'United States',
    'CAN' => 'Canada',
    'MEX' => 'Mexico',
    'BRA' => 'Brazil',
    'ARG' => 'Argentina'
];

$codes = array_keys($countries, 'United States');

print_r($codes);
//['USA']
```

When we added the third parameter, it check if `2` an integer equals `'2'` a string, since they are different, it returns an empty array.

```php
$countries = [
    'one' => 1,
    'two' => '2',
    'three' => 3,
    'four' => 5,
    'six' => 6
];

$codes = array_keys($countries, 2, true);

print_r($codes);
//[]
```

But when we make sure the types are the same, it returns the key.

```php
$countries = [
    'one' => 1,
    'two' => '2',
    'three' => 3,
    'four' => 5,
    'six' => 6
];

$codes = array_keys($countries, '2', true);

print_r($codes);
//[]
```

# `array_values()`

It takes in an associative array and returns all the values in a numerically indexed array.

It accepts one argument, the array.

```php
$smartphones = [
    "Samsung" => "Galaxy S21",
    "Apple" => "iPhone 12",
    "Google" => "Pixel 5"
];

$smartphone_models = array_values($smartphones);

print_r($smartphone_models);
//['Galaxy S21', 'iPhone 12', 'Pixel 5']
```


# `array_merge()`

It takes in two or more arrays and merges them to form one array. It returns the new array.

```php
$terrestrial_planets = ['Mercury', 'Venus', 'Earth', 'Mars'];

$gas_giants = ['Jupiter', 'Saturn', 'Uranus', 'Neptune'];

$all_planets = array_merge($terrestrial_planets, $gas_giants);

print_r($all_planets);

//['Mercury', 'Venus', 'Earth', 'Mars', 'Jupiter', 'Saturn', 'Uranus', 'Neptune']
```

Example with three arrays.

```php

$indoor_hobbies = ['Reading', 'Drawing', 'Cooking', 'Gaming'];

$outdoor_hobbies = ['Hiking', 'Fishing', 'Camping'];

$social_hobbies = ['Dancing', 'Singing', 'Playing instruments'];

$all_hobbies = array_merge($indoor_hobbies, $outdoor_hobbies, $social_hobbies);

print_r($all_hobbies);

//['Reading', 'Drawing', 'Cooking', 'Gaming', 'Hiking', 'Fishing', 'Camping', 'Dancing', 'Singing', 'Playing instruments']
```



# `array_slice()`

It extracts a portion of the array. It literarily takes out a slice of the array, like taking out a slice of bread.

It does not change the value of the array, after the slice operation, the original array remains the same and does not get altered or changed in any way.

It takes in four arguments:

-   A required input array.
-   The starting point of the extraction. This is an integer and is required.
-   The number of items to be extracted. This is an integer and optional, if it is not provided, the function will extract or slice the array from the starting point to the end of the array.
-   An Optional boolean value that determines whether to preserve the keys of the input array or not. If true, the keys will be preserved. If false, the keys will be re-indexed.

```php

$sports = ['Basketball', 'Football', 'Baseball', 'Soccer', 'Tennis', 'Swimming'];

$slice_sports = array_slice($sports, 0);

print_r($slice_sports);
//['Football', 'Baseball', 'Soccer', 'Tennis', 'Swimming']
```

In the code above, the number of items to be extracted is not provided, so the array is extracted from the second value to the last.

**_Note: The array index starts from 0._**

```php

$sports = ['Basketball', 'Football', 'Baseball', 'Soccer', 'Tennis', 'Swimming'];

$middle_sports = array_slice($sports, 2, 2, true);

print_r($middle_sports);
//['Baseball', 'Soccer']
```

In the code above, the starting point is provided and the number of array to be extracted `2` is also provided. The last argument makes sure the extracted array items keep the index they had in the original array.

# `array_reduce()`

It applies a user-defined function iteratively on the item's value, that is, it takes a user-defined function and passes all values in the array through the function one after the other and reduces the array items to a single value.

Its common use is to perform arithmetic operations on a number array but it can also be used to concatenate an array of strings.

It takes in three arguments:

-   A required input array
-   A required user-defined function
-   An optional initial value where the string catenation or the number arithmetic begins with.

Let us add an array of numbers.

```php

$numbers = [1, 2, 3, 4, 5];

function add_numbers($accumulator, $current_value) {
     return $accumulator + $current_value;
}

$sum = array_reduce($numbers, 'add_numbers', 0);

echo $sum; // Output: 15
```

We can set the initial value to any arbitrary number.

```php

$numbers = [1, 2, 3, 4, 5];

function add_numbers($accumulator, $current_value) {
     return $accumulator + $current_value;
}

$sum = array_reduce($numbers, 'add_numbers', 10);

echo $sum; // Output: 25
```

Concatenating a string.

```php

function add_words($prev, $next) {
return $prev . "-" . $next;
}
$pest = ["Dog","Cat","Horse"];
print_r(array_reduce($pest, "add_words", '**'));

//**-Dog-Cat-Horse
```

# `count()`

It counts the number of elements in an array. It returns an integer and takes in two arguments:

-   A required input array.
-   An optional mode flag that can either be `COUNT_NORMAL`, this is the normal counting behavior. it counts in the top-level array only and there is no counting in the nested array. The other is `COUNT_RECURSIVE`, this counts the number of elements in the nested array.

An example using the normal `count()` behavior. You do not need to put `COUNT_NORMAL` flag in the `count()` function to use it, as this is the default.

```php

$oceans = ["Atlantic", "Pacific", "Indian", "Southern", "Arctic"];

$count = count($oceans);

echo "There are $count oceans in the world.";

//There are 5 oceans in the world.
```

Another example using the `COUNT_RECURSIVE` flag. Notice that the function counts the array content first, then adds it to the sum of the nested arrays.

```php

$animals = [
    ["cat", "dog", "horse"],
    ["parrot", "eagle", "ostrich"],
    ["salmon", "tuna", "shark", "octopus"],
    "tiger"
];

$count = count($animals, COUNT_RECURSIVE);
echo "There are $count animals in the zoo.";

//There are 14 animals in the zoo.
```

# `array_reverse()`

It is used to reverse the order of elements in an array. It returns an array of reversed elements and accepts two arguments:

-   A required input array.
-   An optional boolean argument that determines if the new array will preserve its keys or not. This argument is false by default, which means unless otherwise stated, the returned array will have new keys starting from 0.

```php
$courses = ["Math", "English", "Science", "History"];

$reversed = array_reverse($courses);

print_r($reversed);
/*
Array
(
    [0] => History
    [1] => Science
    [2] => English
    [3] => Math
)
*/
```

Here is an example with a preserved key after reversal.

```php
$mountains = ["Everest" => 8848, "K2" => 8611, "Kangchenjunga" => 8586, "Lhotse" => 8516];
$reversed = array_reverse($mountains, true);

print_r($reversed);
/*
[
    "Lhotse" => 8516,
    "Kangchenjunga" => 8586,
    "K2" => 8611,
    "Everest" => 8848
];
*/
```

# Conclusion

Arrays in PHP are used to store multiple values in a single variable. The functions discussed are essential to manipulate and modifying arrays.

Learning about these functions is essential for any PHP developer who works with arrays regularly, as they can simplify complex array operations and save time when dealing with large datasets. Knowing how to use these functions can make it easier to write efficient and effective code, improve performance, and avoid errors when working with arrays in PHP.