PHP - in_array
Trieda
Metóda - in_array
(PHP 4, PHP 5, PHP 7)
The function is used to check the existence of a value in an array.
Procedurálne
- function in_array (mixed $needle, array $haystack, bool $strict = false) : bool
Parametre
| Názov | Dátový typ | Predvolená hodnota | Popis |
|---|---|---|---|
| $needle | mixed | The value for which occurrence we search in the array. If the searched value is a string, it's compared in a case sensitive manner. | |
| $haystack | array | The array in which the value is searched. | |
| $strict | bool | false | If this parameter is set to |
Mávratovej hodnoty
Vracia: bool
In case the searched value is found in the array, the function returns
true, otherwise returns false.
Príklady
If we're searching a string, the searching is case-sensitive.
<?php
$girls = array("Jane","Diana","Alice","Kate","Leila");
echo in_array("Diana",$girls) ? "A string Diana is in the $girls array. <br>" : "A string Diana is NOT in the $girls array. <br>";
echo in_array("diana",$girls) ? "A string diana is in the $girls array. <br>" : "A string diana is NOT in the $girls array. <br>";
If we set the third parameter to true, the function checks also the type of the value.
<?php
$years = array(1970, 1971, 1972, 1975, 1978);
echo in_array(1975, $years) ? "Number 1975 is in the $years array. <br>" : "Number 1975 is NOT in the $years array. <br>";
echo in_array("1975", $years) ? "A string 1975 is in the $years array. <br>" : "A string 1975 is NOT in the $years array. <br>";
echo in_array("1975", $years, true) ? "A string 1975 is in the $years array. <br>" : "A string 1975 is NOT in the $years array.<br>";
A searched value can also be an array.
<?php
$cars = array(array("Mercedes","Audi","BMW"), array("Toyota", "Mazda"));
echo in_array(array("Mercedes", "Audi"), $cars) ? "An array with values Mercedes and Audi is in the $cars array. <br>" : "An array with values Mercedes and Audi is NOT in the $cars array. <br>";
echo in_array(array("Toyota", "Mazda"), $cars) ? "An array with values Toyota and Mazda is in the $cars array. <br>" : "An array with values Toyota and Mazda is NOT in the $cars array. <br>";
echo in_array(array("Mazda", "Toyota"), $cars) ? "An array with values Mazda and Toyota is in the $cars array. <br>" : "An array with values Mazda and Toyota is NOT in the $cars array. <br>";
Súvisiace manuály
- function array_key_exists (mixed $key, array $array) : bool
- function array_search (mixed $needle, array $haystack, bool $strict = false) : mixed
- function isset (mixed $var, mixed $...) : bool
