Denoteone
Denoteone

Reputation: 4055

Check in array if only one specific entry is present

I am trying to check if there is only one value in an array and if that specific value is "Home" then do something. Is the method below the best way to accomplish this or can I do it in one step?

Like:

$mymenu;    // array

if(count($mymenu) < 2 && in_array('Home', $mymenu)){
    // Do something
}

Upvotes: 1

Views: 117

Answers (2)

Zeeshan
Zeeshan

Reputation: 1675

Try this ternary Operator ...

echo count($mymenu) === 1 && $mymenu[0] === 'Home' ? 'Do something' : null;

Upvotes: 0

Danny Beckett
Danny Beckett

Reputation: 20788

The only other changes I'd make would be:

if(count($mymenu) === 1 && $mymenu[0] === 'Home')

Changing the count check from < 2 to === 1 reads better to me; it makes more sense when reading the code back, since it conveys what you actually mean.

As for in_array, since you know there should only be one item in your array, it's probably faster to just use $mymenu[0] instead of doing a needle/haystack lookup.

Other than that, there isn't a more concise way to do what you want.

Upvotes: 3

Related Questions