-2

I have an multidimensional array in which I want a specific value. For example I have an array for images like that:

[img_id] => 19, [crdate] => 0000-00-00 00:00:00, [path] => /Media/19987245_10213822143447913_772090576_n.png,[tags] => funny

I want to echo the path of the image with the img_id = 3.

I thought something like

echo $array[$img_id -> 3]->$path;
Ali Azam
  • 2,047
  • 1
  • 16
  • 25
sotos bic
  • 89
  • 7
  • 9
    Possible duplicate of [PHP multidimensional array search by value](https://stackoverflow.com/questions/6661530/php-multidimensional-array-search-by-value) – iainn Dec 22 '17 at 09:45
  • @iainn isn't there any way to get the path without searching the whole array? I was thinking since I know the id of the image i want i could write an echo like i echo a variable – sotos bic Dec 22 '17 at 09:52
  • If you want to search your array based on something, use it as the array's key. Otherwise, no, you'll need to loop over it. You can re-index an existing array using `array_column`, e.g. `$array = array_column($array, null, 'img_id');` – iainn Dec 22 '17 at 09:54

2 Answers2

0

If you need one liner, here is the one,

$name = $arr[array_search($img_id,array_column($arr, 'img_id'))]['path'];

array_search — Searches the array for a given value and returns the first corresponding key if successful

array_column — Return the values from a single column in the input array

Here is working demo.

Rahul
  • 18,271
  • 7
  • 41
  • 60
0

Traverse the array with the help of for-each loop and check the value of img_id in if-else block. like below code,

foreach($array as $array1){

if($array1['img_id]'==3){
echo $array1['path']; // your answer
}
}
Narayan
  • 1,670
  • 1
  • 19
  • 37