0

This is how I used to create keys that didn't exist inside an array when looping through data:

$array = [];
foreach ($results as $result) {

    if (!isset($array[$result->id])) {
        $array[$result->id] = [];
    }

    $array[$result->id][] = $result->value;
}

A colleague at work does the following. PHP doesn't error but I am not sure if it's a feature of PHP or if it's incorrect:

$array = [];
foreach ($results as $result) {
    $array[$result->id][] = $result->value;
}

Is it incorrect for me to do the above?

1 Answer 1

3

if condition you put in your code is unnecessary. Let me explain.

if (!isset($array[$result->id])) {
    $array[$result->id] = [];
}

This mean if $array[$result->id] is not exist than you are define it as an array, however $array[$result->id][] it self create new array if not existing without throwing any error. So no need to use if condition error. In conclusion, both code are correct, just you are using unnecessary if condition.

Sign up to request clarification or add additional context in comments.

4 Comments

Great! Thank you! Is this a documented PHP feature by any chance? There's no obvious risk that it might be removed one day?
@BenSinclair I can't find any mention of it in the PHP array documentation. But it doesn't even print a warning when it creates the intermediate array, so I think it's intended to work. But I prefer your first version, to make it clear.
@Barmar I did find this but it doesn't explicitly say my example is correct. But it looks like it's possible and doesn't throw an error.
@BenSinclair I think that's the answer, it does say that your example is correct. The key is to understand that it $arr in the example there stands for any expression that denotes something you can assign an array to, so it works with multiple levels of arrays. But note that it also says that it's discouraged.

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.