1

I have the following code which works perfectly fine to give me the name of the customer with the ID of 10:

foreach($customer_list as $row) {
    if ($row->CUSTOMER_ID == 10)
    echo $row->NAME;
}

Is there a way I can do this more directly, without the foreach loop and if statement? I'd like to do something like:

echo $customer_list[CUSTOMER_ID][10]->NAME;

But I don't know the syntax or if it's even possible.

1
  • Where did you get the $customer_list variable? Database call? Commented Jul 17, 2016 at 4:38

3 Answers 3

2

You could use array_filter It will return an array of customers whose ID is 10. We then select the first match (the only match probably) and access the NAME property.

$name = reset( array_filter(
            $customer_list,function($c){return $c->CUSTOMER_ID === 10;}
    ))->NAME;

The cleaner approach is to factor it out, into a separate function:

$getCustName = function($list,$id){
    return reset( array_filter(
        $list,
        function($c) use ($id) {return $c->CUSTOMER_ID === $id;}
    ))->NAME;
};

Then you can get the name easily with just one line:

$name = $getCustName($customer_list,10);
Sign up to request clarification or add additional context in comments.

Comments

0

You can use php array_filter method. Basically you need to pass a function which will check value of customer_Id and returns the element of the array.

Comments

0

you can add your code inside a function and then call that function when you need the name. I am assuming you have unique customer ID's.

function getCustName($customers,$id){
  if(count($customers)>0){
    foreach($customers as $row) {
       if ($row->CUSTOMER_ID == $id)
       return $row->NAME;
    }
  } else{
      return false;
  } 
}

Now if you need to get customer name just call the function

echo getCustName($customer_list,10);

Comments

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.