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

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

WBOY
Release: 2016-07-21 15:39:20
Original
853 people have browsed it

in_array
(PHP 4, PHP 5)

in_array — Check if a value exists in the array

Description

Copy codeThe code is as follows:
bool in_array ( mixed $needle , array $haystack [, bool $strict ] )

Search 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: Prior to PHP version 4.2.0, needle was not allowed to be an array.

Example #1 in_array() >$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



Copy code

The code is as follows:

$a = array('1.10', 12.4, 1.13);
if (in_array('12.4', $a, true)) { echo "'12.4' found with strict checkn"; } if (in_array (1.13, $a, true)) { echo "1.13 found with strict checkn";
}
?>


The above example will output:

1.13 found with strict check


Example #3 Use array as needle in_array()



Copy code

The code is as follows:

$a = array(array('p', 'h'), array('p', 'r'), 'o') ;
if (in_array(array('p', 'h'), $a)) { echo "'ph' was foundn"; } if (in_array( array('f', 'i'), $a)) { echo "'fi' was foundn";
}
if (in_array('o', $a)) {
echo "'o' was foundn";
}
?>


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

Puzzling!

{Weak language}


Solution:

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


http://www.bkjia.com/PHPjc/321552.html
www.bkjia.com
truehttp: //www.bkjia.com/PHPjc/321552.html

TechArticle

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