Search
 
SCRIPT & CODE EXAMPLE
 
CODE EXAMPLE FOR PHP

php get item position in array

//To expand on previous comments, here are some examples of
//where using array_search within an IF statement can go
//wrong when you want to use the array key thats returned.
//Take the following two arrays you wish to search:

<?php
$fruit_array = array("apple", "pear", "orange");
$fruit_array = array("a" => "apple", "b" => "pear", "c" => "orange");

if ($i = array_search("apple", $fruit_array))
//PROBLEM: the first array returns a key of 0 and IF treats it as FALSE

if (is_numeric($i = array_search("apple", $fruit_array)))
//PROBLEM: works on numeric keys of the first array but fails on the second

if ($i = is_numeric(array_search("apple", $fruit_array)))
//PROBLEM: using the above in the wrong order causes $i to always equal 1

if ($i = array_search("apple", $fruit_array) !== FALSE)
//PROBLEM: explicit with no extra brackets causes $i to always equal 1

if (($i = array_search("apple", $fruit_array)) !== FALSE)
//YES: works on both arrays returning their keys
?>
Source by www.php.net #
 
PREVIOUS NEXT
Tagged: #php #item #position #array
ADD COMMENT
Topic
Name
9+5 =