Explanation of PHP Function in_array of

  • 2021-07-13 04:52:15
  • OfStack

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


in_array(value,array,type)
return boolen

Parameter description:
value: Value to search for
array: Array Searched
type: Type, true congruent, false non-congruent (default)

Example 1: General use

Code:


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

Implementation results:

bool(true)

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

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

Implementation results:

bool(true)

Congruent
Code:

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

Implementation results:

bool(false)

Example 3: Cloning Objects
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);

Implementation results:

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);

Implementation results:

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);

Implementation results:
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);

Implementation results:

bool(false)


Related articles: