Finding the Position of a Value in an Array

Use array_search( ) . It returns the key of the found value. If the value is not in the array, it returns false:
 
$position = array_search($value, $array);
if ($position !== false) {
    // the element in position 
//$position has $value as its 
//value in array $array
}
 
Use in_array( ) to find if an array contains a value; use array_search( ) to discover where that value is located. However, because array_search( ) gracefully handles searches in which the value isn't found, it's better to use array_search( ) instead of in_array( ). The speed difference is minute, and the extra information is potentially useful:

$favorite_foods = array(1 => 'artichokes', 'bread', 'cauliflower', 'deviled eggs');
 $food = 'cauliflower'; $position = array_search($food, $favorite_foods);
 if ($position !== false)
{
echo "My #$position favorite food is $food";
}
 else {
 echo "Blech! I hate $food!";
 }


Use the !== check against false because if your string is found in the array at position 0, the if evaluates to a logical false, which isn't what is meant or wanted.
If a value is in the array multiple times, array_search( ) is only guaranteed to return one of the instances, not the first instance.
 
Related Posts:
  • PHP MySQL Functions mysql_field_len — Returns the length of the specified field mysql_field_name — Get the name of the specified field in a result mysql_field_seek — Set result pointer to a specified field offset mysql_field_table — Get … Read More
  • PHP - Echo <?php $myiString = "Hi!"; echo $myiString; echo "<h5>I love PHP!</h5>"; ?>   Display: Hi! I love  PHP!  A simple form example     1 <html> 2 <head> 3 <title&g… Read More
  • PHP Zip File Functions zip_close — Close a ZIP file archive zip_entry_close — Close a directory entry zip_entry_compressedsize — Retrieve the compressed size of a directory entry zip_entry_compressionmethod — Retrieve the compression meth… Read More
  • Creating Arrays PHP provides the array( ) language construct that creates arrays. The following examples show how arrays of integers and strings can be constructed and assigned to variables for later use: $numbers = array(5, 4, 3, 2, 1);… Read More
  • PHP Date / Time Functions checkdate — Validate a Gregorian date date_add — Alias of DateTime::add date_create_from_format — Alias of DateTime::createFromFormat date_create — Alias of DateTime::__construct date_date_set — Alias of DateTime::setDate … Read More
  • CREATING THE DATABASE To create a database, connect to MySQL and run the CREATE DATABASE command. This is theMySQL command to create a database called mydatabase: CREATE DATABASE ’mydatabase’; <?phpdefine(“MYSQLUSER”, “root”);define(“MYSQLP… Read More
  • PHP Variable names Variable names always begin with a dollar sign ($) and are case-sensitive. Here aresome valid variable names:$pill$ad_count$dForce$I_kk_PHP$_underscore$_intHere are some illegal variable names:$not valid$|$3ka  These va… Read More
  • Substrings PHP If you know where in a larger string the interesting data lies, you can copy it out with the substr( ) function: $piece = substr(string, start [, length ]); The start argument is the position in string at which to begin copy… Read More
  • PHP Array array array array([mixed ...]) Creates an array using the parameters as elements in the array. By using the => operator, you can specify specific indexes for any elements; if no indexes are given, the ele… Read More
  • PHP Configuration Directives Although the focus of this book is application security, there are a few configuration directives with which any security-conscious developer should be familiar. The configuration of PHP can affect the behavior of the cod… Read More
  • Length of a String The length property of a string is determined with the strlen( ) function, which returns the number of eight-bit characters in the subject string: integer strlen(string subject) We used strlen( ) earlier in the chapter t… Read More
  • PHP Array Functions array_change_key_case — Changes all keys in an array array_chunk — Split an array into chunks array_combine — Creates an array by using one array for keys and another for its values array_count_values — Counts all the value… Read More
  • Cleaning Strings Often, the strings we get from files or users need to be cleaned up before we can use them. Two common problems with raw data are the presence of extraneous whitespace, and incorrect capitalization (uppercase versus lowercas… Read More
  • PHP HTTP Functions ob_deflatehandler — Deflate output handler ob_etaghandler — ETag output handler ob_inflatehandler — Inflate output handler http_parse_cookie — Parse HTTP cookie http_parse_headers — Parse HTTP headers http_parse_message — P… Read More
  • Comparison Operators for If/Else Statements So far you have just been using the equal comparison operator, but conditional statements are reallychecking to see if a statement evaluates to true, not if something is equal. You can also check to seeif something is not eq… Read More