search
HomeBackend DevelopmentPHP TutorialPHP array operation matching search elements and key names in the array

In the previous article "How to compare strings in PHP? (Detailed explanation of examples) "In "We have introduced in detail the relevant knowledge of how to compare two strings in PHP. In this article, we will take a look at the relevant knowledge of array operations in PHP. I hope it will be helpful to everyone. helpful!

PHP array operation matching search elements and key names in the array

In the previous article we learned that strings can be processed through the strcmp() function and the strcasecmp() function Comparison, string is one of the important data types in PHP. Another very important data type in the PHP development process is array. We have learned that strings can be compared, positioned, replaced, etc., so for the same Do we have any common operations on important arrays?

In the previous article "How to locate elements in strings and arrays in PHP? 》We talked about how to search and locate elements in strings and arrays. We mentioned that you can use the preg_grep() function to locate and search array elements. Let’s take a look at more method to find and search elements in an array.

<strong><span style="font-size: 20px;">in_array</span></strong>() function - matches array elements and returns Boolean

In PHP we can search for elements in the array through the in_array() function. The basic syntax format of the in_array() function is as follows:

in_array(search,array,type)

What needs to be noted is that the parameter search represents the value we need to search in the array, the parameter array represents the array we need to search, and the parameter type is an optional parameter. If the value of the parameter is true, during the search, it will be checked whether the searched data and the searched array data type are the same.

If the value we need to search is found in the array, the result returned by the function is true; if the value we need to search is not found in the array, the result returned The result is false.

Next, let’s look at the application of the in_array() function in PHP through a simple example. The example is as follows:

<?php
$people = array("Bill", "bob", "Mark", "coc");
if (in_array("23", $people, TRUE))
  {
  echo "在数组中";
  }
else
  {
  echo "不在数组中";
  }
  echo &#39;<br/>&#39;;
if (in_array("Mark",$people, TRUE))
  {
  echo "在数组中";
  }
else
  {
  echo "不在数组中";
  }
  echo &#39;<br/>&#39;;
if (in_array("bill",$people, TRUE))
  {
  echo "在数组中";
  }
else
  {
  echo "不在数组中";
  }
?>

Output result:

PHP array operation matching search elements and key names in the array

In the above example, when we searched for the third time, we used lowercase and the match was not successful. What needs to be noted is that if the content we need to search is a string, and the parameter type is set to true, then the search will be case-sensitive.

<strong><span style="font-size: 20px;">array_search</span></strong>() function - matches array elements and returns the key name

The above in_array function knowledge simply searches to determine whether there are elements we need to find in the array. There is no way to locate them. If we want to accurately locate and find them, in PHP we You can use the array_search() function, which can search for elements, and the result returned is the key name of the element we are searching for. The basic syntax format of

array_search() function is as follows:

array_search(value,array,strict)

What needs to be noted is that the parameter value is what we need to search for Key value, parameter array is the array we need to search, parameter strict is an optional parameter, this parameter is flase by default, if the parameter is set If it is true, when searching, it will be checked whether the searched data and the searched array data type are the same.

If the corresponding key value is searched in the array, the returned result is the key name corresponding to the key value; if there is no match, the returned result is false; it needs to be noted that if If more than one key value is matched, the result returned at this time is the key name that matches the key value for the first time.

Let’s take a look at the use of the array_search function through an example. The example is as follows:

<?php
$a=array("a"=>"5","b"=>5,"c"=>"5");
echo array_search(5,$a,true) . &#39;<br/>&#39;;
$array = array(0 => &#39;blue&#39;, 1 => &#39;red&#39;, 2 => &#39;green&#39;, 3 => &#39;red&#39;);
echo array_search(&#39;green&#39;,$array,true);
?>

Output result:

PHP array operation matching search elements and key names in the array

It should be noted that when the parameter is set to true, when searching and matching the array, the search results will be different for different data forms.

<strong><span style="font-size: 20px;">array_key_exists</span></strong>##() function - matches array key name and returns Boolean

In the above, we can use the

array_search function to output the key name of the search element through the search key value. In PHP, we can also directly search the key name. That is through the array_key_exists function in PHP.

array_key_existsThe basic syntax format of the function is as follows:

array_key_exists(key,array)

其中需要注意的是:参数key表示的就是我们需要所搜的键名,参数array标识的就是我们需要进行搜索的数组,

通过array_key_exists函数只能够判断一维数组中的键名不能判断多维数组中数组内的键名,如果在数组中匹配到了指定的键名,该函数返回的结果就是true,如果数组中没有匹配到。返回的结果就是flase。

下面我们通过示例来看一下array_key_exists函数的使用,示例如下:

<?php
$people = array("Bill", "a"=>"bob", "Mark", "coc");
if (array_key_exists(0, $people,))
  {
  echo "键名存在";
  }
else
  {
  echo "键名不存在";
  }
  echo &#39;<br/>&#39;;
if (array_key_exists("a",$people,))
  {
  echo "键名存在";
  }
else
  {
  echo "键名不存在";
  }
  echo &#39;<br/>&#39;;
if (array_key_exists("coc",$people,))
  {
  echo "键名存在";
  }
else
  {
  echo "键名不存在";
  }
?>

输出结果:

PHP array operation matching search elements and key names in the array

由此我们便通过array_key_exists来进行在一个数组中找到一个指定的键。

大家如果感兴趣的话,可以点击《PHP视频教程》进行更多关于PHP知识的学习。

The above is the detailed content of PHP array operation matching search elements and key names in the array. 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
PHP Email: Step-by-Step Sending GuidePHP Email: Step-by-Step Sending GuideMay 09, 2025 am 12:14 AM

PHPisusedforsendingemailsduetoitsintegrationwithservermailservicesandexternalSMTPproviders,automatingnotificationsandmarketingcampaigns.1)SetupyourPHPenvironmentwithawebserverandPHP,ensuringthemailfunctionisenabled.2)UseabasicscriptwithPHP'smailfunct

How to Send Email via PHP: Examples & CodeHow to Send Email via PHP: Examples & CodeMay 09, 2025 am 12:13 AM

The best way to send emails is to use the PHPMailer library. 1) Using the mail() function is simple but unreliable, which may cause emails to enter spam or cannot be delivered. 2) PHPMailer provides better control and reliability, and supports HTML mail, attachments and SMTP authentication. 3) Make sure SMTP settings are configured correctly and encryption (such as STARTTLS or SSL/TLS) is used to enhance security. 4) For large amounts of emails, consider using a mail queue system to optimize performance.

Advanced PHP Email: Custom Headers & FeaturesAdvanced PHP Email: Custom Headers & FeaturesMay 09, 2025 am 12:13 AM

CustomheadersandadvancedfeaturesinPHPemailenhancefunctionalityandreliability.1)Customheadersaddmetadatafortrackingandcategorization.2)HTMLemailsallowformattingandinteractivity.3)AttachmentscanbesentusinglibrarieslikePHPMailer.4)SMTPauthenticationimpr

Guide to Sending Emails with PHP & SMTPGuide to Sending Emails with PHP & SMTPMay 09, 2025 am 12:06 AM

Sending mail using PHP and SMTP can be achieved through the PHPMailer library. 1) Install and configure PHPMailer, 2) Set SMTP server details, 3) Define the email content, 4) Send emails and handle errors. Use this method to ensure the reliability and security of emails.

What is the best way to send an email using PHP?What is the best way to send an email using PHP?May 08, 2025 am 12:21 AM

ThebestapproachforsendingemailsinPHPisusingthePHPMailerlibraryduetoitsreliability,featurerichness,andeaseofuse.PHPMailersupportsSMTP,providesdetailederrorhandling,allowssendingHTMLandplaintextemails,supportsattachments,andenhancessecurity.Foroptimalu

Best Practices for Dependency Injection in PHPBest Practices for Dependency Injection in PHPMay 08, 2025 am 12:21 AM

The reason for using Dependency Injection (DI) is that it promotes loose coupling, testability, and maintainability of the code. 1) Use constructor to inject dependencies, 2) Avoid using service locators, 3) Use dependency injection containers to manage dependencies, 4) Improve testability through injecting dependencies, 5) Avoid over-injection dependencies, 6) Consider the impact of DI on performance.

PHP performance tuning tips and tricksPHP performance tuning tips and tricksMay 08, 2025 am 12:20 AM

PHPperformancetuningiscrucialbecauseitenhancesspeedandefficiency,whicharevitalforwebapplications.1)CachingwithAPCureducesdatabaseloadandimprovesresponsetimes.2)Optimizingdatabasequeriesbyselectingnecessarycolumnsandusingindexingspeedsupdataretrieval.

PHP Email Security: Best Practices for Sending EmailsPHP Email Security: Best Practices for Sending EmailsMay 08, 2025 am 12:16 AM

ThebestpracticesforsendingemailssecurelyinPHPinclude:1)UsingsecureconfigurationswithSMTPandSTARTTLSencryption,2)Validatingandsanitizinginputstopreventinjectionattacks,3)EncryptingsensitivedatawithinemailsusingOpenSSL,4)Properlyhandlingemailheaderstoa

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 Tools

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

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

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version