-5

I am using a foreach loop to echo names from my multi-dimensional array.

Sample Array:

$readJson = [
    [
        'id' => 78,
        'name' => 'audi',
        'sscat_id' => 59,
        'date' => '0000-00-00 00:00:00'
    ],
    [
        'id' => 106,
        'name' => 'apache',
        'sscat_id' => 86,
        'date' => '0000-00-00 00:00:00'
    ],
    [
        'id' => 16,
        'name' => 'asia',
        'sscat_id' => 62,
        'date' => '0000-00-00 00:00:00'
    ]
];

I need to implement a condition whereby if the value of $_GET['b'] exists in the id column of my array, I want to echo that subarray's name value.

If $_GET['b'] does not exist in my array, I want to echo all of the name values in the array.

The is my failing code:

foreach ($readJson as $key => $value){
    if($_GET["b"] === $value["id"]){ // here is statement
        echo $value["name"]; // I want to echo just this item not others
        // maybe break; ?
    } else {
        echo $value["name"]; // echo all items
    }
}

I guess I need something like break but I know break won't echo items after it.

Or if I get item index maybe I could echo it by index or id?

mickmackusa
  • 43,625
  • 12
  • 83
  • 136
Jack The Baker
  • 1,781
  • 1
  • 20
  • 51
  • 1
    Just remove the output in the `else` branch then …? – CBroe Feb 14 '18 at 11:29
  • @CBroe NO! If i do this, if statement is false, it won't show all items – Jack The Baker Feb 14 '18 at 11:30
  • 1
    *"If it matches, `echo` it, else, `echo` it."* – Hmmmmm… – deceze Feb 14 '18 at 11:30
  • Why you put echo in `if` and `else` both statement? Just add `break` under IF condition. – Yash Parekh Feb 14 '18 at 11:31
  • Why down vote? Am I ask strange question?! funny – Jack The Baker Feb 14 '18 at 11:31
  • @YashParekh I told, if I add break it echo all items until that item, and just won't echo items after it. – Jack The Baker Feb 14 '18 at 11:33
  • It's unclear what you're asking… Will there be more than 1 matching item? And you only want to echo the first matching one? Then get rid of the `else` and put a `break` after the `echo` in `if`. If that's not the obvious solution, we have no clue what you expect this to do. – deceze Feb 14 '18 at 11:33
  • You’re not making much sense, what you are asking, resp. what you actually want to achieve here, is unclear. Right now you are outputting the current item in both your if and your else branch - so you get every single item output, no matter whether your condition was actually true or false. You don’t want that, ok - but what _do_ you want then? – CBroe Feb 14 '18 at 11:33
  • Alright guys, let me update my question with an example. – Jack The Baker Feb 14 '18 at 11:34
  • So, to rephrase: *If there is any item in your array that matches `$_GET['b']`, then you want to output that __and only that__ item. If there are no items matching `$_GET['b']` in your array, then you want to output __all items__ instead.* – Does that capture the intent? – deceze Feb 14 '18 at 11:39
  • If that's ☝️ the case, then you need to figure out whether there's any match *before* the loop and *before* you start to output anything. – deceze Feb 14 '18 at 11:40
  • @deceze Yes I exactly want this, Thank you for understanding me! But I don't follow you, *whether there's any match before the loop and before you start to output anything* what do you mean? – Jack The Baker Feb 14 '18 at 11:43
  • @deceze If you say so, How can I create statement when I have not `$value["id"]` outside the loop. `$_GET['b']` equal by **B** so then? – Jack The Baker Feb 14 '18 at 11:52

3 Answers3

1

A concise approach is a lookup array which is an associative array crafted by array_column() which has id values as keys and name values as values. If there is any drawback yo this approach, it is that there is no short circuiting condition. In other words, array_column() will always iterate the full array to populate the lookup, even if the sought value is in the very first row.

Code: (Demo)

$lookup = array_column($readJson, 'name', 'id');
echo $lookup[$_GET["b"]] ?? implode(', ', $lookup);

Output:

asia

When $_GET['b']=99, then output is:

audi, apache, asia

Another sensible approach would be to never iterate the input array more than once and short circuit when appropriate. You can even populate a result array of one or more names then unconditionally implode the array after the loop is broken or otherwise finished. (Demo)

$names = [];
foreach ($readJson as $row) {
    if ($row['id'] === $_GET["b"]) {
        $names = [$row['name']]; // overwrite array with single element
        break;
    }
    $names[] = $row['name'];
}
echo implode(', ', $names);
mickmackusa
  • 43,625
  • 12
  • 83
  • 136
1

Filter the values by matches, if none matched, use all values instead, and output them:

$values = array_filter($readJson, function ($i) { return $i['id'] == $_GET['b']; });

foreach ($values ?: $readJson as $value) {
    echo $value['name'];
}

If $values is empty (== false), $values ?: $readJson falls back to $readJson, otherwise uses $values.

Alternatives might include echo join(', ', array_column($values ?: $readJson, 'name')); depending on what exactly you need to do with those values in the loop.

deceze
  • 510,633
  • 85
  • 743
  • 889
0
    if(array_search($_GET["b"],array_column($readJson, 'id')) !== False)  {
       foreach ($readJson as $key => $value){
         if($_GET["b"]==$value["id"]){
              echo $value["name"];
          }         
       }     
    }else{
      foreach ($readJson as $key => $value){
          echo $value["name"];
       }
    }
Saurabh Mistry
  • 12,833
  • 5
  • 50
  • 71