Home  >  Article  >  Backend Development  >  Instructions for using the php in_array function and instructions for what you need to pay attention to in_array

Instructions for using the php in_array function and instructions for what you need to pay attention to in_array

高洛峰
高洛峰Original
2016-12-22 13:14:441067browse

in_array
(PHP 4, PHP 5)

in_array — Check whether a certain value exists in the array

Description

bool in_array ( mixed $needle , array $haystack [, bool $strict ] )

Search for needle in haystack, if found, return TRUE, otherwise return FALSE.

If the value of the third parameter strict is TRUE, the in_array() function will also check whether the type of needle is the same as that in haystack.

Note: If needle is a string, the comparison is case-sensitive.

Note: Before PHP version 4.2.0, needle was not allowed to be an array.

Example #1 in_array() example

<?php 
$os = array("Mac", "NT", "Irix", "Linux"); 
if (in_array("Irix", $os)) { 
echo "Got Irix"; 
} 
if (in_array("mac", $os)) { 
echo "Got mac"; 
} 
?>

The second condition fails because in_array() is case-sensitive, so the above program is displayed as:
Got Irix

Example #2 in_array() Strict type checking example

<?php 
$a = array(&#39;1.10&#39;, 12.4, 1.13); 

if (in_array(&#39;12.4&#39;, $a, true)) { 
echo "&#39;12.4&#39; found with strict check\n"; 
} 
if (in_array(1.13, $a, true)) { 
echo "1.13 found with strict check\n"; 
} 
?>

The above example will output:

1.13 found with strict check

Example #3 in_array() using array as needle

<?php 
$a = array(array(&#39;p&#39;, &#39;h&#39;), array(&#39;p&#39;, &#39;r&#39;), &#39;o&#39;); 

if (in_array(array(&#39;p&#39;, &#39;h&#39;), $a)) { 
echo "&#39;ph&#39; was found\n"; 
} 
if (in_array(array(&#39;f&#39;, &#39;i&#39;), $a)) { 
echo "&#39;fi&#39; was found\n"; 
} 
if (in_array(&#39;o&#39;, $a)) { 
echo "&#39;o&#39; was found\n"; 
} 
?>

The above example will output:

'ph' was found
'o' was found

Things to note:

If:

First declare an array as:

 $arr = array(*);

Then:

in_array(0, $arr) == true

It’s puzzling! {Weak language}


Solution:
in_array(strval(0), $arr, true))


For more php in_array function usage instructions and in_array notes, please pay attention to PHP Chinese for related articles net!


Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn