search
HomeBackend DevelopmentPHP TutorialPHP determines whether a certain value exists in a multidimensional array_PHP tutorial

Today we will introduce to you how to determine whether the element value we are looking for exists in the array. Here, if it is one-dimensional data, you can directly in_array, but multi-dimensional data is a bit more complicated.

Let’s first solve the problem of in_array checking whether a certain value exists in the array

The code is as follows
 代码如下 复制代码

$os = array("Mac", "NT", "Irix", "Linux");

echo “(1)”;
if (in_array("Irix", $os)) {
    echo "Got Irix";
}
if (in_array("mac", $os)) {//in_array() 是区分大小写的
    echo "Got mac";
}

 

$a = array('1.10', 12.4, 1.13);
echo "(2)";

if (in_array('12.4', $a, true)) {//in_array() 严格类型检查
    echo "'12.4' found with strict checkn";
}
if (in_array(1.13, $a, true)) {
    echo "1.13 found with strict checkn";
}
 

 

$a = array(array('p', 'h'), array('p', 'r'), 'o');
echo "(3)";

if (in_array(array('p', 'h'), $a)) {
    echo "'ph' was foundn";

}

if (in_array(array('f', 'i'), $a)) {//in_array() 中用数组作为 needle
    echo "'fi' was foundn";
}
if (in_array('o', $a)) {
    echo "'o' was foundn";
}
?>

 

程序运行结果是:

(1)Got Irix

(2)1.13 found with strict check

(3)'ph' was found    'o' was found

Copy code


$os = array("Mac", "NT", "Irix", "Linux");
 代码如下 复制代码

$arr = array(
   array('a', 'b'),
   array('c', 'd')
);
 
in_array('a', $arr); // 此时返回的永远都是 false
deep_in_array('a', $arr); // 此时返回 true 值
 
function deep_in_array($value, $array) { 
    foreach($array as $item) { 
        if(!is_array($item)) { 
            if ($item == $value) {
                return true;
            } else {
                continue; 
            }
        } 
         
        if(in_array($value, $item)) {
            return true;    
        } else if(deep_in_array($value, $item)) {
            return true;    
        }
    } 
    return false; 
}

echo “(1)”;

if (in_array("Irix", $os)) {

echo "Got Irix";
} if (in_array("mac", $os)) {//in_array() is case sensitive

echo "Got mac";
}

$a = array('1.10', 12.4, 1.13); echo "(2)"; if (in_array('12.4', $a, true)) {//in_array() strict type checking echo "'12.4' found with strict checkn"; } if (in_array(1.13, $a, true)) { echo "1.13 found with strict checkn"; } $a = array(array('p', 'h'), array('p', 'r'), 'o'); echo "(3)"; if (in_array(array('p', 'h'), $a)) { echo "'ph' was foundn"; } if (in_array(array('f', 'i'), $a)) {//Use array as needle in in_array() echo "'fi' was foundn"; } if (in_array('o', $a)) { echo "'o' was foundn"; } ?> The result of running the program is: (1)Got Irix (2)1.13 found with strict check (3)'ph' was found 'o' was found The above are all one-dimensional arrays. It’s very simple. Let’s see if there is a certain value in the multi-dimensional data
The code is as follows Copy code
$arr = array( array('a', 'b'), array('c', 'd') ); in_array('a', $arr); // The return value at this time is always false deep_in_array('a', $arr); // Returns true value at this time function deep_in_array($value, $array) { foreach($array as $item) { If(!is_array($item)) { If ($item == $value) {                      return true;                 } else { Continue;                }                                                                                                                                                                                           If(in_array($value, $item)) {                  return true;                                                              } else if(deep_in_array($value, $item)) {                 return true;                                                          } }   Return false; } This method is found in the comments under the in_array method detailed explanation page of the PHP help manual. If you have nothing to do, read the help manual more often, especially the classic comments at the end, which collects many people's classic methods.

www.bkjia.comtruehttp: //www.bkjia.com/PHPjc/632800.htmlTechArticleToday we will introduce to you how to determine whether the element value we are looking for exists in the array. Here we will introduce if it is one-dimensional The data is directly in_array but multidimensional data is a little more complicated. Let’s explain it first...
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
PHP Performance Tuning for High Traffic WebsitesPHP Performance Tuning for High Traffic WebsitesMay 14, 2025 am 12:13 AM

ThesecrettokeepingaPHP-poweredwebsiterunningsmoothlyunderheavyloadinvolvesseveralkeystrategies:1)ImplementopcodecachingwithOPcachetoreducescriptexecutiontime,2)UsedatabasequerycachingwithRedistolessendatabaseload,3)LeverageCDNslikeCloudflareforservin

Dependency Injection in PHP: Code Examples for BeginnersDependency Injection in PHP: Code Examples for BeginnersMay 14, 2025 am 12:08 AM

You should care about DependencyInjection(DI) because it makes your code clearer and easier to maintain. 1) DI makes it more modular by decoupling classes, 2) improves the convenience of testing and code flexibility, 3) Use DI containers to manage complex dependencies, but pay attention to performance impact and circular dependencies, 4) The best practice is to rely on abstract interfaces to achieve loose coupling.

PHP Performance: is it possible to optimize the application?PHP Performance: is it possible to optimize the application?May 14, 2025 am 12:04 AM

Yes,optimizingaPHPapplicationispossibleandessential.1)ImplementcachingusingAPCutoreducedatabaseload.2)Optimizedatabaseswithindexing,efficientqueries,andconnectionpooling.3)Enhancecodewithbuilt-infunctions,avoidingglobalvariables,andusingopcodecaching

PHP Performance Optimization: The Ultimate GuidePHP Performance Optimization: The Ultimate GuideMay 14, 2025 am 12:02 AM

ThekeystrategiestosignificantlyboostPHPapplicationperformanceare:1)UseopcodecachinglikeOPcachetoreduceexecutiontime,2)Optimizedatabaseinteractionswithpreparedstatementsandproperindexing,3)ConfigurewebserverslikeNginxwithPHP-FPMforbetterperformance,4)

PHP Dependency Injection Container: A Quick StartPHP Dependency Injection Container: A Quick StartMay 13, 2025 am 12:11 AM

APHPDependencyInjectionContainerisatoolthatmanagesclassdependencies,enhancingcodemodularity,testability,andmaintainability.Itactsasacentralhubforcreatingandinjectingdependencies,thusreducingtightcouplingandeasingunittesting.

Dependency Injection vs. Service Locator in PHPDependency Injection vs. Service Locator in PHPMay 13, 2025 am 12:10 AM

Select DependencyInjection (DI) for large applications, ServiceLocator is suitable for small projects or prototypes. 1) DI improves the testability and modularity of the code through constructor injection. 2) ServiceLocator obtains services through center registration, which is convenient but may lead to an increase in code coupling.

PHP performance optimization strategies.PHP performance optimization strategies.May 13, 2025 am 12:06 AM

PHPapplicationscanbeoptimizedforspeedandefficiencyby:1)enablingopcacheinphp.ini,2)usingpreparedstatementswithPDOfordatabasequeries,3)replacingloopswitharray_filterandarray_mapfordataprocessing,4)configuringNginxasareverseproxy,5)implementingcachingwi

PHP Email Validation: Ensuring Emails Are Sent CorrectlyPHP Email Validation: Ensuring Emails Are Sent CorrectlyMay 13, 2025 am 12:06 AM

PHPemailvalidationinvolvesthreesteps:1)Formatvalidationusingregularexpressionstochecktheemailformat;2)DNSvalidationtoensurethedomainhasavalidMXrecord;3)SMTPvalidation,themostthoroughmethod,whichchecksifthemailboxexistsbyconnectingtotheSMTPserver.Impl

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

DVWA

DVWA

Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

EditPlus Chinese cracked version

EditPlus Chinese cracked version

Small size, syntax highlighting, does not support code prompt function

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools