How to get specific value from array?

时间:2022-12-21 11:08:59

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:

我想要的具体值是2和5,所以数组将是这样的:

$newArray = array("2","5");

Thanks.

3 个解决方案

#1


2  

Since "0" is falsey you can just use array_filter to remove all the "0" from your array:

由于“0”是假的,你可以使用array_filter从数组中删除所有“0”:

$array = array("0","2","0","5","0","7","0");
$newArray = array_filter($array); // newArray is: ["2", "5", "7"]

#2


0  

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

#3


0  

You can use array_filter

您可以使用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
)

Demo

#1


2  

Since "0" is falsey you can just use array_filter to remove all the "0" from your array:

由于“0”是假的,你可以使用array_filter从数组中删除所有“0”:

$array = array("0","2","0","5","0","7","0");
$newArray = array_filter($array); // newArray is: ["2", "5", "7"]

#2


0  

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

#3


0  

You can use array_filter

您可以使用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
)

Demo