array_search
snippet in php

how to search for a value in an array php

user1259

<?php 
// PHP function to illustrate the use of array_search() 
function Search($value, $array) 
{ 
    return(array_search($value, $array)); 
} 
$array = array("ram", "aakash", "saran", "mohan", "saran"); 
$value = "saran"; 
print_r(Search($value, $array)); 
?> 

array_search

user3466

// array demo

public $gender = array(
  1 => 'Male',
  2 => 'Female',
  3 => 'Other',
);

$gen = 1;

if ($gen == array_search('Male', $this->gender)) {
  $gender = __d('member', 'male');

} elseif ($gen  == array_search('Female', $this->gender)) {
  $gender = __d('member', 'female');

}

array_search

user7541


<?php
$array = array(0 => 'blue', 1 => 'red', 2 => 'green', 3 => 'red');

$key = array_search('green', $array); // $key = 2;
$key = array_search('red', $array);   // $key = 1;
?>