2

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

1
  • Looks good apart from the missing ; on first line Commented Mar 29, 2013 at 16:16

3 Answers 3

3

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

Sign up to request clarification or add additional context in comments.

2 Comments

@cpattersonv1 $k is always set. Either with false if $needle is not found, or with a key value to indicate where to find $needle in $haystack array. Check the manual page for array_search for more information.
@cpattersonv1 The parentheses are there for a good reason. I don't see why you would want to remove them.
0

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

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

1 Comment

No he's missing the triple equals sign. This won't work if the matched element has a key of 0.
0

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

}



?>

Comments

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.