Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I check if a key/value pair exists in php?

Tags:

php

I am getting a list of schools for each athlete. If an athlete has a status of committed: true in the object, I only want to show that school. Otherwise, I want to return all properties.

This is what my data looks like:

...
"offers": [
    {
        "school": "Foo School",
        "committed": true
      },
      {
        "school": "Bar School",
        "committed": false
      }
    ]
...

In the above example, I only want to show "Foo School". But if both committed properties were false I want to show "Foo Schoo" and "Bar School".

Here is what I have currently, but am returning both regardless.

foreach ($object['athlete']['offers'] as $offer) {
    if (isset($offer['committed']) && $offer['committed'] == 1) {
       // return single school
    } else {
       // push into array & return?
    }
}

Thank you for any suggestions!

like image 684
Damon Avatar asked Oct 24 '25 04:10

Damon


1 Answers

I think this is what you were looking for, please correct me if I'm wrong. If all of them are false, then it returns all. If one or more are true, it returns the first one that's true:

<?php

$offers = array(
    array("school" => "Foo School",
    "committed" => true
  ),
  array(
    "school" => "Bar School",
    "committed" => false
  ));

$fullReturn = "";
$flag = false;
foreach ($offers as $offer) {
    if (isset($offer['committed']) && $offer['committed']) {
       echo $offer['school'];
       $flag = true;
       break;
    } else {
       $fullReturn .= $offer['school'] . "<br />";
    }
}

if (!$flag) {
    echo $fullReturn;
}

?>
like image 144
Neil Avatar answered Oct 25 '25 19:10

Neil