Home >Backend Development >PHP Tutorial >In-depth analysis of in_array() function in PHP

In-depth analysis of in_array() function in PHP

autoload
autoloadOriginal
2021-04-19 09:36:064089browse

In-depth analysis of in_array() function in PHP

PHPArray is a common data type. We often put data sets into arrays, but in subsequent data verification Sometimes, due to the complexity of the data, the space and time complexity will be greatly increased through traversal. PHP has a built-in in_array() function to help us solve this trouble. This article will bring Come and take a look.

First, let’s take a look at the syntax knowledge of the in_array() function:

in_array ( mixed $needle , array $haystack , bool $strict = false )
  • $needle: the value to be searched.

  • $haystack: Array to be searched.

  • $strict: If true, it will check whether the type of $needle is the same as that in $haystack, that is, "==="

  • Return value: Return true if $needle is found, otherwise return false.

# Secondly, let’s take a look at its use in the actual process.

1. Use two parameters by default

<?php
$os = array("Mac", "Windows", "Unix", "Linux");

if (in_array("Irix", $os)) {
    echo "得到了 Irix";
}else{
     echo "没有  Irix";
}

echo "<br>";
if (in_array("mac", $os,false) ){
    echo "有mac";
}else{
     echo "没有mac";
}
?>
输出:没有 Irix
      没有mac

We will find that in_array() is case-sensitive.

2. Use three parameters by default

<?php
$os = array("Mac", "Windows", "11", "Linux");

if (in_array("11", $os)) {
    echo "得到了 11";
}else{
     echo "没有  11";
}

echo "<br>";
if (in_array(11, $os,true) ){
    echo "有11";
}else{
     echo "没有11";
}
?>
输出:得到了 11
        没有11

If not set $strict , loose comparison will be used. If set, A value of true also checks whether the types are the same.

Recommendation: 2021 PHP interview questions summary (collection)》《php video tutorial

The above is the detailed content of In-depth analysis of in_array() function in PHP. For more information, please follow other related articles on the PHP Chinese website!

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