0

I am trying to match two strings using foreach loop in php ( laravel framework).

$c_act = "ABC123";
foreach ($codes as $cd) {
      $ac = $cd->Code;       //ac holds our Activity code

      if ($ac==$c_act) {
           $act_id = $cd->ID; 
        }
}

here $codes holds data from my values with ID and Code.Its

 [{"ID":"7","Code":"ABC-1"},{"ID":"8","Code":"ABC-OBT"},{"ID":"12","Code":"ABCD"}]

If the first variable is not a match, then I need to go back to foreach loop and start with the next value I have. I tried, But couldn't complete it.
How to do this using php?
Thanks in advance

7
  • simply you can user in_array() function Commented Oct 6, 2016 at 5:45
  • @PradyutManna - Look at the question, he got an array with objects. in_array won't cut it... Commented Oct 6, 2016 at 5:46
  • @Anant - That doesn't really answer his question? Commented Oct 6, 2016 at 5:48
  • @MagnusEriksson there is a function get_object_vars() that convert object to array Commented Oct 6, 2016 at 5:49
  • @anat That's what I had tried, but, it fails go back for next value, if the first is not a mactch Commented Oct 6, 2016 at 5:50

1 Answer 1

2

Try using this code:

$act_id = null;
$c_act = "ABC123";
foreach ($codes as $cd) {
    $ac = $cd->Code;       //ac holds our Activity code
    if ($ac==$c_act) {
        $act_id = $cd->ID;
        break;
    }
}

if($act_id === null){
    // there was no match
}else{
    // there was a match, and the ID is stored in $act_id
}
Sign up to request clarification or add additional context in comments.

2 Comments

@Sachith i have added one
@Sachith i don't see any reason why your code shouldn't already work

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.