PHP: echo item from array by its value instead of by its array index

109 Views Asked by At

I have an array with two values stored for each item, the first one called "ID" and the second one called "en". The ID values are unique integers and the en values are text.

Now I would like to echo a specific item from the array referring to it by its ID.

I tried the below but this goes by the index within the array so it gives me a different item than what I need.

Can someone tell me how I can echo e.g. the item with ID = 10 instead of the item with the array index = 10 (here it currently gives me Value11 instead of Value1) ?

My PHP:

<?php echo $arr[10]["en"]; ?>

The array:

Array ( 
        [0] => Array ([ID] => 10 [en] => Value1 ),
        [1] => Array ([ID] => 11 [en] => Value2 ),
        [2] => Array ([ID] => 12 [en] => Value3 ),
        // ...
        [10] => Array ([ID] => 20 [en] => Value11 ),
        // ...
      )

Many thanks in advance, Mike

2

There are 2 best solutions below

5
On BEST ANSWER

I think you want that when you pass any value it will check that where the value exist at id index of your multidimensional array and give it's key and it's en index value.

<?php

$array = Array ( 
        '0' => Array ('ID' => 10, 'en' => 'Value1' ),
        '1' => Array ('ID' => 11, 'en' => 'Value2' ),
        '2' => Array ('ID' => 12, 'en' => 'Value3' )
        );
function findKeyandValue($array,$value){

   foreach($array as $key=>$val){
    if($val['ID']== $value){
        echo 'key of the value pass='.$key.'and its en value is'.$val['en'].'<br>';
    }
}

}

findKeyandValue($array,10);
?>

Output:- https://eval.in/382010

14
On
function FindByID($arr, $id) {
  foreach($arr as $item) {
   if ($item['ID'] === $id) return $item['en'];
  } 
  return null;
}

echo FindByID($arr, 11);