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

高洛峰
Release: 2023-03-03 22:02:01
Original
1075 people have browsed it

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 ] )
Copy after login

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"; 
} 
?>
Copy after login

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"; 
} 
?>
Copy after login

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"; 
} 
?>
Copy after login

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!


Related labels:
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template