php-laravelHow can I filter an array in a Laravel application using PHP?
In order to filter an array in a Laravel application using PHP, you can use the array_filter function. This function takes a callback function as its first argument, which is used to determine whether a value should be included in the resulting array or not.
$array = [1, 2, 3, 4, 5];
$filteredArray = array_filter($array, function ($value) {
return $value % 2 === 0;
});
print_r($filteredArray);
Output example
Array
(
[1] => 2
[3] => 4
)
The code above filters out all odd numbers from the $array and stores the resulting array in the $filteredArray variable. The callback function checks each element of the array to see if it is divisible by 2 ($value % 2 === 0) and returns true if it is, or false otherwise.
The array_filter function can also be used to filter an associative array, where the key-value pairs are preserved.
$assocArray = [
'a' => 1,
'b' => 2,
'c' => 3,
'd' => 4,
'e' => 5
];
$filteredAssocArray = array_filter($assocArray, function ($value) {
return $value % 2 === 0;
});
print_r($filteredAssocArray);
Output example
Array
(
[b] => 2
[d] => 4
)
The code above filters out all odd numbers from the $assocArray and stores the resulting array in the $filteredAssocArray variable.
Helpful links
More of Php Laravel
- How do I decide between using PHP Laravel and Yii for my software development project?
- How can I convert JSON data to XML using PHP Laravel?
- How do Laravel and Symfony compare in terms of developing applications with PHP?
- How do I use the GROUP BY clause in a Laravel query using PHP?
- How can I use the PHP Zipstream library in a Laravel project?
- ¿Cómo configurar PHP y Laravel desde cero?
- How do I set up a .gitlab-ci.yml file for a Laravel project using PHP?
- How can I get the current year in PHP Laravel?
- How do I configure Xdebug in the php.ini file for a Laravel project?
- How do I install Laravel using XAMPP and PHP?
See more codes...