0

I have this array:

$predmeti = [
        'slo' => [
            'ime' => 'Slovenščina',
            'ucitelj' => 'Ana Berčon',
            'nadimek' => '',
            'ucilnica' => '11'
        ],
        'mat' => [
            'ime' => 'Matematika',
            'ucitelj' => 'Nevenka Kunšič',
            'nadimek' => '',
            'ucilnica' => '12'
        ],
        'ang' => [
            'ime' => 'Angleščina',
            'ucitelj' => 'Alenka Rozman',
            'nadimek' => 'Rozi',
            'ucilnica' => '3'
        ]
];

How do I get each value for slo, mat, ang etc. with foreach loop? I just know how to get key and value in foreach, but not in this nested array.

3 Answers 3

1

Why not just:

foreach($predmeti as $v) {
    echo $v['ime'];
    //etc...
}

or:

foreach($predmeti as $k => $v) {
    echo $k;
    echo $v['ime'];
    //etc...
}
Sign up to request clarification or add additional context in comments.

Comments

1

I assume you're talking about the second level array, to get that you do another foreach inside:

foreach($predmeti as $key => $value) {
    foreach($value as $sub => $second) {
        echo $sub . ' -> ' . $second . PHP_EOL;
    }
}

Comments

0

Use foreach (array_expression as $key => $value) syntax:

foreach ($predmeti as $key => $value) {
    echo $key;
}

These values are the $key of each array inside of $predmeti.

From the manual:

The foreach construct provides an easy way to iterate over arrays. foreach works only on arrays and objects, and will issue an error when you try to use it on a variable with a different data type or an uninitialized variable. There are two syntaxes:

foreach (array_expression as $value)
    statement
foreach (array_expression as $key => $value)
    statement

1 Comment

@elusive sure is. Thanks for the catch.

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.