PHP/Data Structure/array key exists

Материал из Web эксперт
Перейти к: навигация, поиск

Checking a <select> menu submission value

 
if (! array_key_exists($_POST["order"], $GLOBALS["sweets"])) {
    $errors[] = "Please choose a valid order.";
}



Checking for an element with a particular key

 
<?
$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";
}
?>



Testing for the Existence of a Key in an Array

 
<?php 
$countries = array("Germany" => "German", "France" => "French", "Spain" => "Spanish"); 
$country = "asdf"; 
printf("<p>%s of our visitors are from %s.</p>\n", array_key_exists($country, $countries) ? "Some" : "None", $country); 
?>



Validating a drop-down menu with array_key_exists()

 
<?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.";
}
?>