polo7
polo7

Reputation: 57

How to get key by searching a specific value in php array

I just want to obtain the key by searching with the value id_img=17. This is the array:

$array_test = array (
0  => array("id_img" => 18, "desciption" => "Super image", "author" => "Person 1"),
1  => array("id_img" => 17, "desciption" => "Another image", "author" => "Person 2"),
2  => array("id_img" => 22, "desciption" => "The last image", "author" => "John Doe"),
);

Thanks for your help.

Upvotes: 1

Views: 427

Answers (4)

Robert Rossmann
Robert Rossmann

Reputation: 12131

I like to do things without foreach or for loops if possible, out of purely personal preference.

Here's my go for this:

$array_test = array (
    0  => array("id_img" => 18, "desciption" => "Super image", "author" => "Person 1"),
    1  => array("id_img" => 17, "desciption" => "Another image", "author" => "Person 2"),
    2  => array("id_img" => 22, "desciption" => "The last image", "author" => "John Doe"),
);

$result = array_filter( $array_test, function( $value )
{
    return $value['id_img'] == 17 ? true : false;
});
$key = array_keys( $result )[0];

print_r( $key );

Instead of loops, I use array_filter() to get only those items in the array that match my rule ( as defined in the Closure's return statement ). Since I know I only have one ID with value of 17 I know I will end up with only one item in the $result array. Then I retrieve the first element from the array keys ( using array_keys( $result )[0] ) - That's the key which holds the id_img = 17 in the original array.

Upvotes: 1

heiligster
heiligster

Reputation: 126

Try:

$array_test = array (
0  => array("id_img" => 18, "desciption" => "Super image", "author" => "Person 1"),
1  => array("id_img" => 17, "desciption" => "Another image", "author" => "Person 2"),
2  => array("id_img" => 22, "desciption" => "The last image", "author" => "John Doe"),
);

$result = null;

foreach($array_test as $key => $val )
{
  if( $val['id_img'] == 17 )
    $result = $key;

}
return $result;

Upvotes: 0

maxton
maxton

Reputation: 392

function getKey($arr,$value){
  foreach($arr as $key=>$element) {
    if($element["id_img"] == $value)
      return $key;
  }
  return false;
}

Upvotes: 1

Jerzy Zawadzki
Jerzy Zawadzki

Reputation: 1985

<?php
$found=false;
$searched=17;
foreach($array_test as $k=>$data)
 if($data['id_img']==$searched)
   $found=$key;

And you've got your key in $found var or false if it's not found

Upvotes: 0

Related Questions