You want to know if an array contains a certain key.
Use array_key_exists() to check for a key no matter what the associated value is. This fnction ignores array values. It just reports whether there is an element in the array with a particular key.
Use isset() to find a key whose associated value is anything but null. A null value causes the funtion to return false.
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="EN" lang="EN"> <head> <title>PHP</title> <meta Name="Author" Content="Hann So"> </head> <body> <p> <?php $fruits = array('red'=>'Apples', 'green'=>'Grapes', 'yellow'=>'Bananas', 'orange'=>'Oranges'); print_r($fruits); echo "<p><b>Use array_key_exists() to check.</b></p>"; if (array_key_exists('green', $fruits)) { echo "The value for green key is ", $fruits['green'], ".<br />"; } else { echo "There's no green key.<br />"; } if (array_key_exists('black', $fruits)) { echo "The value for green key is ", $fruits['black'], ".<br />"; } else { echo "There's no black key.<br />"; } echo "<p><b>Use array_key_exists() to check.</b></p>"; if (isset($fruits['green'])) { echo "The value for green key is ", $fruits['green'], ".<br />"; } else { echo "There's no green key.<br />"; } if (isset($fruits['black'])) { echo "The value for gree key is ", $fruits['black'], ".<br />"; } else { echo "There's no black key.<br />"; } ?> </p> </body> </html> |