Index of array where value not equal

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
dimxasnewfrozen
Forum Commoner
Posts: 84
Joined: Fri Oct 30, 2009 1:21 pm

Index of array where value not equal

Post by dimxasnewfrozen »

I have a set of database values where all but one of the values will not equal 0.

I need to find the index of the array where this occurs (without doing a massive if statement)

Code: Select all

$levels = array($results["APP_S1_ID"][0],
		      $results["APP_S2_ID"][0],
		      $results["APP_S3_ID"][0],
		      $results["APP_S4_ID"][0],
		      $results["APP_S5_ID"][0]);
	
$l = array_search($levels, !=0); 
echo $l;
User avatar
AbraCadaver
DevNet Master
Posts: 2572
Joined: Mon Feb 24, 2003 10:12 am
Location: The Republic of Texas
Contact:

Re: Index of array where value not equal

Post by AbraCadaver »

You need to give an actual var_dump() of your array. Also, only one value is 0 or only one value is NOT 0, and by NOT 0, does that mean greater or less than zero, or some other string value or what?

Just for fun if you know there is only one non zero:

Code: Select all

$l = current(array_diff(array_flip($levels), array_keys($levels, 0)));
If you're looking for not zero, not empty string, not false, not null:

Code: Select all

$l = array_search(true, $levels);
mysql_function(): WARNING: This extension is deprecated as of PHP 5.5.0, and will be removed in the future. Instead, the MySQLi or PDO_MySQLextension should be used. See also MySQL: choosing an API guide and related FAQ for more information.
Post Reply