caseyy
caseyy

Reputation: 55

array_search Boolean return values

I have been struggling with array_search for a bit and although I think I understand it now, I just want to make absolutely sure I understand the logic behind the way my code is executing.

I am trying to write a function that will add an element to an array if it is not in the array to begin with, and remove it if it is. Simple, right?

$k = array_search($needle, $haystack)
if ( $k === FALSE ) {
    $haystack[] = $needle;
} else {
    unset($haystack[$k]);
}

Is this the most efficient way to write this? It seems like there should be a way to assign the value of $k and at the same time check whether its value is FALSE or anything else (including 0)?

Upvotes: 2

Views: 4218

Answers (3)

AbsoluteƵERØ
AbsoluteƵERØ

Reputation: 7880

Outside of wrapping it with a function so you can reuse it, what you have works well. Most of the other examples are just rewriting what you've written already.

<?php
$haystack = array(
'5','6','7',
);

$needles = array('3','4','2','7');
print_r($haystack);


function checker($needle,$haystack){
    $k = array_search($needle, $haystack);
    if ( $k === FALSE ) {
        $haystack[] = $needle;
    } else {
        unset($haystack[$k]);
    }
    return $haystack;
}


foreach($needles as $value){
    $haystack = checker($value,$haystack);
    print_r($haystack);

}



?>

Upvotes: 0

Jocelyn
Jocelyn

Reputation: 11413

You can shorten your code this way:

if (($k = array_search($needle, $haystack)) === FALSE) {
    $haystack[] = $needle;
} else {
    unset($haystack[$k]);
}

The first line of code performs the search, stores the returned value in $k, and checks if this value is exactly equal to FALSE or not.

Documentation: array_search

Upvotes: 3

Vivek Sadh
Vivek Sadh

Reputation: 4268

Your code is fine but you can do it this way:-

if (($k = array_search($needle, $haystack)) == FALSE) 
{
$haystack[] = $needle;
} 
else 
{
unset($haystack[$k]);
}

Upvotes: 0

Related Questions