php get index of array code example
Example 1: php all keys in array
<?php
$array = array(
'fruit1' => 'apple',
'fruit2' => 'orange',
'fruit3' => 'grape',
'fruit4' => 'apple',
'fruit5' => 'apple');
$keys = array_keys($array);
$values = array_values($array);
?>
Example 2: get index of element in array php
$array = array(0 => 'blue', 1 => 'red', 2 => 'green', 3 => 'red');
$key = array_search('green', $array);
$key = array_search('red', $array);
Example 3: get key of value array php
<?php
$array = array(0 => 'blue', 1 => 'red', 2 => 'green', 3 => 'red');
$key = array_search('green', $array);
$key = array_search('red', $array);
?>
Example 4: get key of array element php
$people = array(
2 => array(
'name' => 'John',
'fav_color' => 'green'
),
5=> array(
'name' => 'Samuel',
'fav_color' => 'blue'
));
$found_key = array_search('blue', array_column($people, 'fav_color'));
Example 5: php array get value at index
$array = array('foo' => 'bar', 33 => 'bin', 'lorem' => 'ipsum');
$array = array_values($array);
echo $array[0];
echo $array[1];
echo $array[2];
Example 6: array search by key in php
$arr = array(
"one" => 1,
"two" => 2,
"three" => 3,
"seventeen" => 17
);
function find($mot){
global $arr;
$ok=false;
foreach ($arr as $k => $v)
{
if($k==$mot){
return $v; $ok=true;
}
}
if(ok==false){ return -1; }
}
echo find("two");