Home > Backend Development > PHP Problem > What are the ways to find a value in an array in php

What are the ways to find a value in an array in php

青灯夜游
Release: 2023-03-15 11:40:01
Original
4637 people have browsed it

Search method: 1. Use the "in_array($search,$arr,$type)" statement; 2. Use the "array_search($search,$arr,$type)" statement; 3. Use "array_key_exists" ($search,$arr)" statement.

What are the ways to find a value in an array in php

The operating environment of this tutorial: Windows 7 system, PHP version 8.1, DELL G3 computer

php search array Method of a certain value

Method 1: Use the in_array() function

The in_array() function searches whether the specified value exists in the array.

<?php
header("Content-type:text/html;charset=utf-8");
$people = array("Peter", "Joe", "Glenn", "Cleveland");
if(in_array("Glenn",$people)){
  echo "找到指定值";
}else{
  echo "没有找到指定值";
}
?>
Copy after login

What are the ways to find a value in an array in php

Method 2: array_search() function

array_search() function is the same as in_array(), searching for an item in the array key value. If the value is found, the key of the matching element is returned. If not found, returns false.

<?php
$a=array("a"=>"Dog","b"=>"Cat","c"=>5,"d"=>"5");
echo array_search("Dog",$a);
echo array_search("5",$a);
?>
Copy after login

What are the ways to find a value in an array in php

Method 3: Use the array_key_exists() function

array_key_exists() function to check whether the specified key exists in an array name, returns true if the key name exists, false if the key name does not exist.

<?php
header("Content-type:text/html;charset=utf-8");
$a=array("a"=>"Dog","b"=>"Cat");
if(array_key_exists("a",$a)){
    echo "Key exists!";
}else{
    echo "Key does not exist!";
}
?>
Copy after login

What are the ways to find a value in an array in php

Recommended learning: "PHP Video Tutorial"

The above is the detailed content of What are the ways to find a value in an array in php. For more information, please follow other related articles on the PHP Chinese website!

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