Reputation: 233
I have an array like this:
$Array = array("0","2","0","5","0");
and the specific value I want is 2 and 5, so the array will be like this:
$newArray = array("2","5");
Thanks.
Upvotes: 0
Views: 267
Reputation: 141935
Since "0"
is falsey you can just use array_filter to remove all the "0" from your array:
$array = array("0","2","0","5","0","7","0");
$newArray = array_filter($array); // newArray is: ["2", "5", "7"]
Upvotes: 2
Reputation: 30488
You can use array_filter
function fil($var)
{
if($var == 2 || $var == 5)
return($var);
}
$array1 = array(0,2,0,5,0);
print_r(array_filter($array1, "fil"));
Output
Array
(
[1] => 2
[3] => 5
)
Upvotes: 0
Reputation: 3288
So you basically just want to remove zero's from your array? I think this should work you just pass the function the array and the item you wish to replace (note this code is untested you may need to tweak it a little)
function array_replace($incomingarray, $tofind)
{
$i = array_search($tofind, $incomingarray);
if ($i === false) {
return $incomingarray;
} else {
unset($incomingarray[$i]);
return array_replace($incomingarray, $tofind);
}
}
$Array = array("0","2","0","5","0");
$a = array_replace($Array, 0);
var_dump($a);
Upvotes: 0