Home  >  Article  >  Backend Development  >  Detailed explanation of the use of PHP function in_array()

Detailed explanation of the use of PHP function in_array()

高洛峰
高洛峰Original
2016-12-22 13:19:081566browse

PHP has a system function is_array() that can determine whether a value is in an array.
The syntax is as follows:

in_array(value,array,type)
return boolen

Parameter description:
value: the value to be searched
array: the array being searched
type: type, true congruent, false non-congruent (default)


Example 1: Normal use

Code:

$str = 1;
 
$arr = array(1,3,5,7,9);
 
$boolvalue = in_array($str,$arr);
 
var_dump($boolvalue);

Execution result:

bool(true)

Example 2: Using the third parameter
Non-congruent
Code:

$str = '1';
 
$arr = array(1,3,5,7,9);
 
$boolvalue = in_array($str,$arr,false);
 
var_dump($boolvalue);

Execution result:

bool(true)

Congruent
Code:

$str = '1';
 
$arr = array(1,3,5,7,9);
 
$boolvalue = in_array($str,$arr,true);
 
var_dump($boolvalue);

Execution result:

bool(false)

Example 3: Clone object
Code:

class a {
    public $a = 1;  
    public function fun(){
        return $this->a; 
    }
}
 
class b {
    public $a = 2;  
    public function fun(){
        return $this->a; 
    }
}
 
$a = new a();
$b = new b();
 
$c = clone $a;
 
$arr = array($a,$b);
 
$boolvalue = in_array($c,$arr,false);
 
var_dump($boolvalue);

Execution result:

bool(true)

Code:

class a {
    public $a = 1;  
    public function fun(){
        return $this->a; 
    }
}
 
class b {
    public $a = 2;  
    public function fun(){
        return $this->a; 
    }
}
 
$a = new a();
$b = new b();
 
$c = clone $a;
 
$arr = array($a,$b);
 
$boolvalue = in_array($c,$arr,true);
 
var_dump($boolvalue);

Execution result:

bool(false)

Example 4: Multidimensional array
Code:

$str = 10;
 
$arr = array(
    array(1,2,3,4),
    array(5,6,7,8,9),
    10
);
 
$boolvalue = in_array($str,$arr);
 
var_dump($boolvalue);

Execution result:

bool(true)

Code:

$str = 10;
 
$arr = array(
    array(1,2,3,4),
    array(5,6,7,8,9,10),
);
 
$boolvalue = in_array($str,$arr);
 
var_dump($boolvalue);

Execution result:

bool(false)


For more detailed explanations on the use of PHP function in_array() and related articles, please pay attention to 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