-1

I want to get a specific value of a variable from multi array, if the condition matches.

When I print my array:

print_r($myarray);

gives array like this:

Array
(
  [0] => Array
   (
     [id] => 21 //check for this value
     [customer_id] => 12456 //get this value 
     [date] => 12-06-2017         
   )
  [1] => Array
   (
     [id] => 15
     [customer_id] => 12541 
     [date] => 12-06-2017
   )
  [2] => Array
   (
     [id] => 12
     [customer_id] => 25415
     [date] => 12-06-2017
   )
)

I am trying to get customer number if the ID matches with 21

foreach ($myarray as $array){
  if($array[][id] == "21"){ //this is where I'm making mistake
    $cust_id = $myarray[]['customer_id'];
    return $cust_id;
  }
}
Arun
  • 300
  • 2
  • 13

3 Answers3

4

Since you are looping through the array you already have a single item. So just do it this way

foreach ($myarray as $array) {
  if ($array["id"] == "21") {
    return $array["customer_id"];
  }
}
pbaldauf
  • 1,671
  • 2
  • 23
  • 32
0

You can create a custom function and call it, like this

function arraySearch($theArray, $searchKey, $searchValue, $returnKey){

    foreach($theArray as $value){
            if($value[$searchKey] == $searchValue)  return $value[$returnKey]; //found, return the value of the choosen $returnKey var
    }

     return false; //not found, so return false

}

and then use it

echo arraySearch($myarray, 'id', '21', 'customer_id'); // it returns 12456

EXAMPLE

Oscar Zarrus
  • 790
  • 1
  • 9
  • 17
0
foreach ($myarray as $array){
  if($array["id"] == 21){
    $cust_id = $array['customer_id'];
    return $cust_id;
  }
}
tdjprog
  • 706
  • 6
  • 11
  • Code-only answers are low value posts on StackOverflow. Please improve your answer with how it works and why it is an appropriate solution. – mickmackusa Dec 22 '17 at 21:05