In this tutorial we will learn array function in laravel.
Array functions in laravel
Laravel is a popular PHP framework that comes with several built-in functions to work with arrays.
Here are some commonly used array functions in Laravel:
1) array_add:
This function adds a key-value pair to an array.
Example:
$array = ['name' => 'John', 'age' => 30];
$newArray = array_add($array, 'gender', 'male');
Output:
$newArray = ['name' => 'John', 'age' => 30, 'gender' => 'male'];
2) array_except:
This function returns an array without the specified keys.
Example:
$array = ['name' => 'John', 'age' => 30, 'gender' => 'male'];
$newArray = array_except($array, ['gender']);
Output:
$newArray = ['name' => 'John', 'age' => 30];
3) array_first:
This function returns the first element of an array that passes the given truth test.
Example:
$array = [10, 20, 30, 40];
$first = array_first($array, function ($value) {
return $value > 25;
});
Output:
$first = 30;
4) array_last:
This function returns the last element of an array that passes the given truth test.
Example:
$array = [10, 20, 30, 40];
$last = array_last($array, function ($value) {
return $value > 25;
});
Output:
$last = 40;
5) array_pluck:
This function returns an array of values from a given key.
Example:
$array = [
['name' => 'John', 'age' => 30],
['name' => 'Jane', 'age' => 25],
['name' => 'Bob', 'age' => 40]
];
$names = array_pluck($array, 'name');
Output:
$names = ['John', 'Jane', 'Bob'];
6) array_sort:
This function sorts an array by its values.
Example:
$array = [10, 30, 20, 40];
$newArray = array_sort($array);
Output:
$newArray = [10, 20, 30, 40];
These are just a few of the array functions available in Laravel. You can find a full list of available array functions in the Laravel documentation.