PHP/Data Structure/in array

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

Checking for an element with a particular value

 
<?
$meals = array("A" => 1,
               "B" => 4.95,
               "C" => 3.00,
               "D" => 6.50,
               "E" => 0); 
$books = array("F","G");

if (in_array(3, $meals)) {
  print "There is a $3 item.";
}
if (in_array("F", $books)) {
  print "We have F";
}
// in_array() is case-sensitive
if (in_array("f", $books)) {
  print "We have the f.";
}
?>



Determining Whether an Element Is in an Array

 
<?php 
$countries = array("Germany" => "German", "France" => "French", "Spain" => "Spanish"); 
$language = "Spanish"; 
printf("<p>%s of our visitors speak %s.</p>\n", in_array($language, $countries) ? "Some" : "None", $language); 
$language = "asdfasd"; 
printf("<p>%s of our visitors speak %s.</p>\n", in_array($language, $countries) ? "Some" : "None", $language); 

?>



in_array() function is a control statement.

 
<?
$language = "French";
$languages = array ("English", "Gaelic", "Spanish");
if (in_array($language, $languages)) :
     print "$language edition.";
else :
     print "We don"t yet offer a $language edition";
endif;
?>



in_array( ) function return true if an array contains a specific value

 
//bool in_array ( mixed needle, array haystack [, bool strict] )
<?
    $needle = "Sam";
    $haystack = array("Johnny", "Timmy", "Bobby", "Sam", "Tammy", "Joe");
    if (in_array($needle, $haystack)) {
            print "$needle is in the array!\n";
    } else {
            print "$needle is not in the array\n";
    }
?>



Locating Array Elements

 
//in_array() function determines whether or not an element exists in an array, returning true if it does, 
//and false otherwise. 
//Its syntax is: bool in_array(mixed element, array array)
<?
    $languages = array ("English", "Gaelic", "Spanish");
    $exists = in_array("Russian", $languages); 
    print $exists;
    print "<BR>";
    $exists = in_array("English", $languages); 
    print $exists;
?>