0

I need to get index of from array of objects without using loop as per the key name using PHP. Here I am explaining my code below.

$arr = array(array("name"=>"Jack","ID"=>10),array("name"=>"Jam","ID"=>11),array("name"=>"Joy","ID"=>12));
$key = array_search('Jack', $arr);

echo $key;exit;

Here my code does not give any output. By using some key name I need the index of that object present inside array and also I dont want to use any loop. I need Is ther any PHP in build method so that I can get the result directly.

2 Answers 2

2
$arr = array(array("name"=>"Jack","ID"=>10),array("name"=>"Jam","ID"=>11),array("name"=>"Joy","ID"=>12));

function myfunction($v){return  $v['name'];}
echo array_search('Jack', array_map( 'myfunction', $arr ));
Sign up to request clarification or add additional context in comments.

Comments

0
<?php
$arr = array(array("name"=>"Jack","ID"=>10),array("name"=>"Jam","ID"=>11),array("name"=>"Joy","ID"=>12));

//calling function searchByName
$key = searchByName('Jasck',$arr);

if($key != '-1'){
  print_r($arr[$key]);  
}else{
    echo "No match found";
}

//function to chek if the name is there or not.
function searchByName($name, $array) {
   foreach ($array as $key => $val) {
       if ($val['name'] == $name) {
           return $key;
       }
   }
   return '-1';
}

sandbox

1 Comment

You used again here loop.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.