Search code examples
phparraysmultidimensional-arrayconditional-statementsarray-column

Print one value from qualifying row or else all values from a specific column


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?


Solution

  • 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);