Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Remove zero values from a PHP array

Tags:

arrays

php

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

like image 726
Elitmiar Avatar asked Feb 18 '10 09:02

Elitmiar


People also ask

How do I get rid of array 0?

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.

How do you remove Blank values from an array?

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.

What does Array_splice () function do give an example?

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).

What is Array_map function in PHP?

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.


4 Answers

array_filter does that. If you don’t supply a callback function, it filters all values out that equal false (boolean conversion).

like image 138
Gumbo Avatar answered Oct 15 '22 01:10

Gumbo


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]);   } } 
like image 24
Jon Winstanley Avatar answered Oct 15 '22 01:10

Jon Winstanley


bit late, but copy & paste:

$array = array_filter($array, function($a) { return ($a !== 0); });
like image 43
Slav Avatar answered Oct 15 '22 02:10

Slav


You can use this:

$result = array_diff($array, [0]);   
like image 30
Amir Fo Avatar answered Oct 15 '22 02:10

Amir Fo