PHP/Data Structure/array key exists

Материал из Web эксперт
Версия от 10:02, 26 мая 2010; Admin (обсуждение | вклад) (1 версия)
(разн.) ← Предыдущая | Текущая версия (разн.) | Следующая → (разн.)
Перейти к: навигация, поиск

Checking a <select> menu submission value

   <source lang="html4strict">

if (! array_key_exists($_POST["order"], $GLOBALS["sweets"])) {

   $errors[] = "Please choose a valid order.";

}

 </source>
   
  


Checking for an element with a particular key

   <source lang="html4strict">

<? $meals = array("A" => 1,

              "B" => 4.95,
              "C" => 3.00,
              "D" => 6.50,
              "E" => 0); // Shrimp Puffs are free!

$books = array("F","G"); if (array_key_exists("A",$meals)) {

   print "Yes, we have A";

} if (array_key_exists("B",$meals)) {

   print "We have a B";

} if (array_key_exists(1, $books)) {

   print "Element 1 is How to Cook in Eat in Chinese";

} ?>

 </source>
   
  


Testing for the Existence of a Key in an Array

   <source lang="html4strict">

<?php $countries = array("Germany" => "German", "France" => "French", "Spain" => "Spanish"); $country = "asdf";

printf("

%s of our visitors are from %s.

\n", array_key_exists($country, $countries) ? "Some" : "None", $country);

?>

 </source>
   
  


Validating a drop-down menu with array_key_exists()

   <source lang="html4strict">

<?php $choices = array("eggs" => "E",

                "toast" => "T",
                "coffee" => "C");

echo "<select name="food">\n"; foreach ($choices as $key => $choice) {

  echo "<option value="$key">$choice</option>\n";

} echo "</select>"; if (! array_key_exists($_POST["food"], $choices)) {

   echo "You must select a valid choice.";

} ?>

 </source>