0

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.

3
  • 1
    If you have the values already why do you need to retrieve them from the array? Commented Jun 26, 2013 at 15:11
  • [2, 5] is not a "specific value." You've filtered elements from your array. This type of operation is called a "Filter", because it removes some elements of the array based on a given rule. In this case, the value must equal 2 or 5. You may want to rephrase your question to something more like "How can I filter this array to retain only certain given values?" Commented Jun 26, 2013 at 15:12
  • I'll go even simpler: $newArray = array($Array[1], $Array[3]); Since we're being vague about the qualifiers. Commented Jun 26, 2013 at 15:18

3 Answers 3

2

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"]
Sign up to request clarification or add additional context in comments.

Comments

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

Comments

0

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
)

Demo

1 Comment

Nice solution using it as a call back. Could get complex if using a variable match params though surely as he'd have to generate the if clauses on the fly?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.