Searching Arrays

We will create a form that lets the user type in either a state or the abbreviation. we will look first to see if the value entered is a key, if so we print the element of the array.

$states=array('AL'=>'Alabama','AK'=>'Alaska','AZ'=>'Arizona','AR'=>'Arkansas','CA'=>'California', 'CO'=>'Colorado', 'CN'=>'Connecticut');

If we don't find it as a key, we will look to see if it a value. If so we print out the key;

if(isset($button)) {
	if(isset($states[$state])) echo $state.' is the abbreviation for '.$states[$state].'<BR>';
	else {
		$s=array_search($state,$states);
		if($s!="") echo 'The abbreviation for '.$state.' is '.$s.'<BR>';
		else echo $state.' NOT FOUND<BR>';
	}
}
You can see this example at http://www.zebra0.com/php-mysql/testing/states.php The text version is at http://www.zebra0.com/php-mysql/testing/states.txt
INDEX, Arrays: Introduction, Create form from array, Arrrays
Next lesson: StringsMAIN INDEX
EXAMPLES INDEX

Copyright © Zebra0.com
All rights reserved worldwide.

 
 

Arrrays