search in an array php code example

Example 1: array_search in php

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

Example 2: array_search

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

}

Example 3: how to lookup value object php

function lookup($array, $key) {

    //loop through all values in array
    foreach($array as $values) {

        //if 'key' value matches `$key`, return 'value' value.
        if($values['key'] == $key) {
            return $values['value'];
        }

    }

    //if nothing has been returned, return empty string
    return "";
}

Example 4: array_search in php

<?php
$a = [
'Canceled' => 1,
'Traded / Filled'=> 2,
'(Not used currently)'=> 3,
'Transit'=> 4,
'Rejected'=> 5,
'Pending'=> 6,
];
echo array_search("5",$a);
?>

Tags:

Php Example