If I have an array $abc=[0,0,0,1,0,2];
how to change it to $abc=[1,2]; (remove all 0), is there php function can handle that? thanks.

$abc_ = array(0, 0, 0, 1, 0, 2);
while( list($key, $value) = each($abc_) )
if( !($value=='0') )
$abc[] = $value;

There may be more efficient (execution time?) code than above.

here is the one of the simplest example...

$abc=[0,0,0,1,0,2];
$bcd=array();
for($i=0;$i<count($abc);$i++)
{
if($abc[$i]!="0")
{
array_push($bcd,$abc[$i])
}
}

i am not saying the urs is wrong but mine is more simpler and easier to understand in one look..

If I have an array $abc=[0,0,0,1,0,2];
how to change it to $abc=[1,2]; (remove all 0), is there php function can handle that? thanks.

Im wondering...

Is this any faster?

<?php 

function removeVal($array, $val) {

    $string = implode(',', $array);
    $new_string = str_replace($val.',', ',', $string);
    $new_array = explode(',', $new_string);

    return $new_array;

}

$abc=[0,0,0,1,0,2];
$new_abc = removeVal($abc, 0);

var_dump($new_abc); // should show new array withought 0s

?>

what do you guys think?... :?:

btw: I think the for loop would be faster...
If you just took the count out of the for loop.

$abc=[0,0,0,1,0,2];
$bcd=array();
$count = count($abc);
for($i=0;$i<$count;$i++)
{
if($abc[$i]!="0")
{
array_push($bcd,$abc[$i])
}
}

This way the count is only evaluated once during the loop.
Im not sure if its faster than the while loop though. :)

I've looked at some benchmark tests. And it seems foreach is fastest. If you just make sure you do not copy the array, but supply the original array ie: &$array.

If I have an array $abc=[0,0,0,1,0,2];
how to change it to $abc=[1,2]; (remove all 0), is there php function can handle that? thanks.

Heres a way of doing this that seems to be the most efficient.
The $new_array also retains its key values.

function removeVals($var) {
    return ($var != 0);
}

$new_array = array();
$array = array(0,0,0,1,0,2);
$new_array = array_filter($array, "removeVals");
This article has been dead for over six months. Start a new discussion instead.