I have a normal array like this
Array
(
[0] => 0
[1] => 150
[2] => 0
[3] => 100
[4] => 0
[5] => 100
[6] => 0
[7] => 100
[8] => 50
[9] => 100
[10] => 0
[11] => 100
[12] => 0
[13] => 100
[14] => 0
[15] => 100
[16] => 0
[17] => 100
[18] => 0
[19] => 100
[20] => 0
[21] => 100
)
I need to remove all 0's from this array, is this possible with a PHP array function
Approach: Mark the first non-zero number's index in the given array. Store the numbers from that index to the end in a different array. Print the array once all numbers have been stored in a different container.
Answer: Use the PHP array_filter() function You can simply use the PHP array_filter() function to remove or filter empty values from an array. This function typically filters the values of an array using a callback function.
The array_splice() function removes selected elements from an array and replaces it with new elements. The function also returns an array with the removed elements. Tip: If the function does not remove any elements (length=0), the replaced array will be inserted from the position of the start parameter (See Example 2).
The array_map() is an inbuilt function in PHP and it helps to modify all elements one or more arrays according to some user-defined condition in an easy manner. It basically, sends each of the elements of an array to a user-defined function and returns an array with new values as modified by that function.
array_filter
does that. If you don’t supply a callback function, it filters all values out that equal false (boolean conversion).
You can just loop through the array and unset any items that are exactly equal to 0
foreach ($array as $array_key => $array_item) { if ($array[$array_key] === 0) { unset($array[$array_key]); } }
bit late, but copy & paste:
$array = array_filter($array, function($a) { return ($a !== 0); });
You can use this:
$result = array_diff($array, [0]);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With