key of array php code example
Example 1: php keys of array
$array = array(0 => 100, "cor" => "vermelho");
print_r(array_keys($array));
$array = array("azul", "vermelho", "verde", "azul", "azul");
print_r(array_keys($array, "azul"));
$array = array("cor" => array("azul", "vermelho", "verde"),
"tamanho" => array("pequeno", "medio", "grande"));
print_r(array_keys($array));
Example 2: get key by 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 3: array key value php
<?php
$age=array("Peter"=>"35","Ben"=>"37","Joe"=>"43");
foreach($age as $x=>$x_value)
{
echo "Key=" . $x . ", Value=" . $x_value;
echo "<br>";
}
?>
Example 4: php get array key
<?php
$array = array(
'fruit1' => 'apple',
'fruit2' => 'orange',
'fruit3' => 'grape',
'fruit4' => 'apple',
'fruit5' => 'apple');
while ($fruit_name = current($array)) {
if ($fruit_name == 'apple') {
echo key($array).'<br />';
}
next($array);
}
?>