/    Sign up×
Community /Pin to ProfileBookmark

Booleans and array_search

So I’ve read the section on php.net about array_search returning a non-Boolean false which can evaluate to 0 which is kind of stupid because it can also return a value of 0 as the key for the element being searched if the function actually returns a true. This makes it difficult to use in an if statement and I’m not sure how to go about it. I can’t use the equality (===) operator because I am not looking for a specific value, just a true value. Can anyone help me out?

Example of code that I am using:

[code=php]
if(isset($_GET[‘video’]) && !empty($_GET[‘video’]) && array_search($_GET[‘video’],$validVideos) >= 0) {
showVideo($_GET[‘video’]);
} else {
[/code]

Where $validVideos is an array of all the possible valid values that $_GET[‘video’] is allowed to be. If $_GET[‘video’] is not a valid video identifier, or $_GET[‘video’] is not set, then I’ll just go to a different page.

I’ve already tried just using array_search($_GET[‘video’],$validVideos) as a statement itself to see if it evaluated to true, but it doesn’t. I’m quite stuck.

to post a comment
PHP

3 Comments(s)

Copy linkTweet thisAlerts:
@TJ111Jan 30.2008 — You can use the in_array() function if possible (although yours should work from what I see). in_array() just returns a boolean, so it would probably be better here anyway.
[code=php]
//...
in_array($_GET['video'],$validVideos)[/code]
Copy linkTweet thisAlerts:
@aj_nscauthorJan 30.2008 — in_array()......what an oversight on my part. thanks a lot for pointing out the obvious, array_search is for when you need the index of a specific value, not what I was looking for, in_array is when you are trying to determing if the value is present...bingo!! much appreciated.
Copy linkTweet thisAlerts:
@NogDogJan 31.2008 — Just to answer your original issue, you can use the "!==" (not identical) operator to check that you did not get a boolean false result.
[code=php]
if(array_search($_GET['video'],$validVideos) !== false) {
[/code]
×

Success!

Help @aj_nsc spread the word by sharing this article on Twitter...

Tweet This
Sign in
Forgot password?
Sign in with TwitchSign in with GithubCreate Account
about: ({
version: 0.1.9 BETA 5.28,
whats_new: community page,
up_next: more Davinci•003 tasks,
coming_soon: events calendar,
social: @webDeveloperHQ
});

legal: ({
terms: of use,
privacy: policy
});
changelog: (
version: 0.1.9,
notes: added community page

version: 0.1.8,
notes: added Davinci•003

version: 0.1.7,
notes: upvote answers to bounties

version: 0.1.6,
notes: article editor refresh
)...
recent_tips: (
tipper: @AriseFacilitySolutions09,
tipped: article
amount: 1000 SATS,

tipper: @Yussuf4331,
tipped: article
amount: 1000 SATS,

tipper: @darkwebsites540,
tipped: article
amount: 10 SATS,
)...