- Удалить пустые элементы из массива в PHP
- 1. Использование array_filter() функция
- Remove Empty Array Elements in PHP
- Use array_filter() Function to Remove the Empty Array Elements in PHP
- Use array_diff() Function to Remove the Empty Array Elements in PHP
- Use unset() Function to Remove the Empty Array Elements in PHP
- Related Article — PHP Array
- How to Remove Empty Array Elements in PHP
- Describing the array_filter Function
- How to remove empty array elements using PHP
- Handy short guide on how to remove empty array elements using PHP.
- Quick solution
- To remove empty array elements
- Using array_filter() to remove empty array elements
- How does array_filter() work?
- Optional callback for extra removal functionality
- Tips: Additional array elements cleaning
- Final thoughts
- You might also like
- References
- How to Remove Empty Array Elements in PHP
- Describing the array_filter Function
Удалить пустые элементы из массива в PHP
В этой статье показано, как удалить пустые элементы из массива в PHP.
1. Использование array_filter() функция
The array_filter() функция удаляет все ложные значения из массива, если функция обратного вызова не указана. Ложное значение в PHP является логическим false , целое число 0 , плавать 0.0 а также -0.0 , нить «0» а также «» , тип агрегата NULL и пустой массив. Следует отметить, что переменная ресурса и NAN не считаются ложными в PHP.
Если предусмотрена функция обратного вызова, будут удалены только те элементы массива, которые не удовлетворяют указанному предикату. Например, следующий код удаляет только пустые строки ( «» ) и NULL значения из массива.
Выражение array_filter($arr) эквивалентно array_filter($arr, function($val)) . Вы можете добавлять или удалять элементы из предиката по мере необходимости. Например, следующее включает 0 от ложных значений.
Вы можете использовать array_filter() Функция для удаления только определенного элемента из массива. Например, следующее удаляет только пустые строки ( «» ) из массива.
Вы также можете использовать array_filter() используя встроенные функции PHP в качестве обратного вызова. Например, в следующем решении используется strlen() функционирует как обратный вызов и удаляет пустые строки ( «» ), false , а также NULL из массива, но игнорирует true , 0 , 0.0 , а также «0» . Это потому, что strlen() функция возвращает нулевое значение для «» , false , а также NULL , но ненулевое значение для true , 0 , 0.0 , а также «0» .
Remove Empty Array Elements in PHP
- Use array_filter() Function to Remove the Empty Array Elements in PHP
- Use array_diff() Function to Remove the Empty Array Elements in PHP
- Use unset() Function to Remove the Empty Array Elements in PHP
In this article, we will introduce methods to remove the empty array elements in PHP.
Use array_filter() Function to Remove the Empty Array Elements in PHP
The built-in function array_filter() removes all the empty elements, zeros, false and null values from an array. This function uses a callback function to filter the array values. If no callback function is specified, it removes the empty elements, zeros, false and null values.
The correct syntax to use this function is as follows
array_filter($arrayName, $callbackFunction, $callbackParameter)
Here the $arrayName is the only mandatory parameter. The parameter $callbackFunction is the callback function specified for the operation on the array. The parameter $callbackParameter tells about the parameters passed to the callback function.
php //Declare the array $flowers = array( "Rose", "Lili", "Jasmine", 0, "Hibiscus", "", "Tulip", null, "Sun Flower", "Daffodil", "Daisy"); $flowers = array_filter($flowers); echo "The array is:\n"; print_r($flowers); ?>
We have not specified any callback function, hence the returned array has no empty elements, zeros, and null values.
The array is: Array ( [0] => Rose [1] => Lili [3] => Jasmine [4] => Hibiscus [6] => Tulip [8] => Sun Flower [10] => Daffodil [11] => Daisy )
Use array_diff() Function to Remove the Empty Array Elements in PHP
The built-in function array_diff() is used to find the difference between two or more arrays . It can be used to delete empty elements from an array. It does not re-index the array. The correct syntax to use this function is as follows.
array_diff($array1, $array2, $array3, . , $arrayN);
It takes N number of the parameters (arrays). It compares the first array with all other arrays. It returns an array that contains all the elements of the first array that are not present in other arrays.
php //Declare the array $flowers = array( "Rose", "Lili", "Jasmine", 0, "Hibiscus", "", "Tulip", null, "Sun Flower", "Daffodil", "Daisy"); $flowers = array_diff($flowers, array("",0,null)); echo "The array is:\n"; print_r($flowers); ?>
Here, we have compared our array with an array that contains the empty string, 0, and null value. Then the returned array has no empty elements.
The array is: Array ( [0] => Rose [1] => Lili [3] => Jasmine [4] => Hibiscus [6] => Tulip [8] => Sun Flower [10] => Daffodil [11] => Daisy )
Use unset() Function to Remove the Empty Array Elements in PHP
The unset() function removes the value stored in a variable. We can use it to remove the empty elements from an array. The correct syntax to use this function is as follows.
It only accepts one parameter $variableName . The $variableName is a variable of which we want to remove the value.
php //Declare the array $flowers = array("Rose","Lili","","Jasmine","Hibiscus","Tulip","Sun Flower","","Daffodil","Daisy"); foreach($flowers as $key => $link) if($link === '') unset($flowers[$key]); > > echo "The array is:\n"; print_r($flowers); ?>
Here, we have used a foreach loop to find the empty array elements. If an array element is empty, its index along with array name is passed as a parameter to the unset() function.
The array is: Array ( [0] => Rose [1] => Lili [3] => Jasmine [4] => Hibiscus [5] => Tulip [6] => Sun Flower [8] => Daffodil [9] => Daisy )
Related Article — PHP Array
How to Remove Empty Array Elements in PHP
Frequently, some elements in an array can be empty, and it is necessary to remove them. In this short tutorial, we will provide you with the right function to do that.
The most common and correct way is to use the array_filter function. It will remove any element that is evaluated as FALSE (null, false, », 0). By adding a callback function, you can customize the filter.
Here is how the array_filter works:
$array = [0, 'amir', 'test', 490, null, '', 'Hello world']; $array = array_filter($array); var_dump($array); ?>
array(4) < [1] =>string(4) "amir" [2] => string(4) "test" [3] => int(490) [6] => string(11) "Hello world" >
In the example above, the value of $array is what is demonstrated below it in the brackets.
That operates properly but may leave index gaps inside an array. Luckily, you can fix it with the help of array_values for re-indexing the array like this:
$array = [0, 'amir', 'test', 490, null, '', 'Hello world']; $array = array_values(array_filter($array)); var_dump($array); ?>
array(4) < [0] =>string(4) "amir" [1] => string(4) "test" [2] => int(490) [3] => string(11) "Hello world" >
In this example, as well, the value of $array is what is demonstrated below it in the brackets.
Describing the array_filter Function
This function is capable of iterating over every value in the array and pass them to the callback function.
Once the callback function returns True, the current value from the array gets back into the result array.
The array_filter function has the following parameters: array, callback, and flag.
The first one is the array to iterate over. Callback is the callback function to apply. And, the flag specifies what arguments are forwarded to the callback.
How to remove empty array elements using PHP
Handy short guide on how to remove empty array elements using PHP.
Quick solution
This function will simply loop through the array and return the elements that are not empty, achieving the result we wanted. To better understand this function, below are more detail instructions.
To remove empty array elements
Using array_filter() to remove empty array elements
The basic method to remove empty array elements in a PHP array is using array_filter() function. Assuming we have this array with various empty elements:
$colors = ['red', 'blue', '', 'green', '', 'yellow'];
We wanted to only keep the array elements containing values and remove empty ones. This can be done easily using array_filter() :
// Remove all empty array elements $colors = array_filter($colors); // the array is now ['red', 'blue', 'green', 'yellow']
How does array_filter() work?
Based on PHP.net official documentation on array_filter() function, the function works by accepting minimum of one argument – the array to filter:
array_filter(array $array, ?callable $callback = null, int $mode = 0)
- $array is the array we want to filter
- $callback is the callback function to loop through the array. If no $callback is supplied, all empty entries of array will be removed. That’s how empty array elements are removed.
However, sometimes this function doesn’t work as expected – the assuming empty elements aren’t removed. Why is it? Because it depends on how PHP treats what is empty with the empty() function. There are blank Unicode values that are a spacing, null values that are not treated as empty, therefore not being removed.
How can we sort this issue? That’s when extra callback is useful.
Optional callback for extra removal functionality
Using callback to remove empty array elements will help cases with elements having special characters not being treated as ’empty’, or simply as the character ‘0’ (that we wanted to remove) to be fully removed from the array.
We will create the callback function first. Based on PHP.net documentation, If the callback function returns true , the current value from array is returned into the result array. So we need to return true on the elements we want to keep, which is the valid elements:
// Function to actually keep and remove the elements we don't want function remove_empty( $value ) < // If $value is not empty (valid), keep it (returns true), else (empty), remove it (returns false) // -or- if $value is not equals '0' (valid), keep it (returns true), else (is '0'), remove it (returns false) return !empty($value) || $value !== '0'; >
Then, we can pass the callback function into the actual array_filter() function:
$colors = array_filter( $colors, 'remove_empty' );
Tips: Additional array elements cleaning
There might be blank spaces in your array elements that aren’t counted as ’empty’ defined by PHP, which you can try to trim the spaces using trim() function with array_map() first before cleaning the array:
// Trim the array elements, removing blank spaces on all elements $colors = array_map( 'trim', $colors ); // Do the filter $colors = array_filter( $colors );
Final thoughts
These are the guide to remove empty array elements using PHP, with some extra tips on cleaning the array elements before filtering it. We hope that this short guide would help you using array_filter() and array_map() effectively.
You might also like
References
How to Remove Empty Array Elements in PHP
Frequently, some elements in an array can be empty, and it is necessary to remove them. In this short tutorial, we will provide you with the right function to do that.
The most common and correct way is to use the array_filter function. It will remove any element that is evaluated as FALSE (null, false, », 0). By adding a callback function, you can customize the filter.
Here is how the array_filter works:
$array = [0, 'amir', 'test', 490, null, '', 'Hello world']; $array = array_filter($array); var_dump($array); ?>
array(4) < [1] =>string(4) "amir" [2] => string(4) "test" [3] => int(490) [6] => string(11) "Hello world" >
In the example above, the value of $array is what is demonstrated below it in the brackets.
That operates properly but may leave index gaps inside an array. Luckily, you can fix it with the help of array_values for re-indexing the array like this:
$array = [0, 'amir', 'test', 490, null, '', 'Hello world']; $array = array_values(array_filter($array)); var_dump($array); ?>
array(4) < [0] =>string(4) "amir" [1] => string(4) "test" [2] => int(490) [3] => string(11) "Hello world" >
In this example, as well, the value of $array is what is demonstrated below it in the brackets.
Describing the array_filter Function
This function is capable of iterating over every value in the array and pass them to the callback function.
Once the callback function returns True, the current value from the array gets back into the result array.
The array_filter function has the following parameters: array, callback, and flag.
The first one is the array to iterate over. Callback is the callback function to apply. And, the flag specifies what arguments are forwarded to the callback.