PHP/Data Structure/array key exists
Содержание
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);
?>
<?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.";
}
?>