Mark Lester
Mark Lester

Reputation: 21

How to echo Array within array?

Hi guys I'm just wondering how can I print out set of arrays using foreach? Here's my simple code.

<?php

function names_job() {

    $names = array();

    $names['lester'] = array('web developer' => 'name1', 'web designer' => 'name2', 'eating' => 'name2');
    $names['joanna'] = 'web designer';
    $names ['chloe'] = 'student';

    return $names;
}

function display_arr() {

    $names_jobs = names_job();

    foreach( $names_jobs as $name => $job ) {
        echo '<br>Name: ' . $name . ' Job: ' . $job . '<br>';

        foreach( $job as $jobs => $boss ) {
            echo '<br>-- ' . $jobs . ' ' . $boss . '<br>';
        }
    }
}
display_arr();

?>

The result from above code is this:

Name: lester Job: Array
web developer name1
web designer name2
eating name2
Name: joanna Job: web designer

Warning: Invalid argument supplied for foreach() in C:\xampp\htdocs\code\index.php on line 21
Name: chloe Job: student

Warning: Invalid argument supplied for foreach() in C:\xampp\htdocs\code\index.php on line 21

Upvotes: 2

Views: 148

Answers (3)

solick
solick

Reputation: 2345

i do not understand why you have set up the structure of your array like this.

But give you an answer to your question: You are walking threw an array an expecting every part of the array to be another arry where the only the first entry in your array are one. Joana and Chloe are normal strings therefore trying to treat them as an arry causes an error.

You could use is_array() to check wether an object or variable is an array and than treat it like needed.

Regards Solick

Upvotes: 0

lulyon
lulyon

Reputation: 7225

Not all $job, the value of $names_jobs, are arrays. That is way you get

Name: lester Job: Array
web developer name1
web designer name2
eating name2

in the first pass, but get warnings in the second pass, in which $job is not an array.

Now I realize the above answer(by @Mark Resølved) has given solid revised code.

Upvotes: 0

gherkins
gherkins

Reputation: 14983

You need to check if $job is an array, before trying to iterate over it. This will also prevent it from being outputted as a string ("Array").

You can use PHPs is_array() function for that: http://php.net/manual/de/function.is-array.php

function display_arr() {

    $names_jobs = names_job();

    foreach( $names_jobs as $name => $job ) {
        echo '<br>Name: ' . $name;

        if( is_array( $job ){
            foreach( $job as $jobs => $boss ) {
                echo '<br>-- ' . $jobs . ' ' . $boss . '<br>';
            }
        }
        else{
            echo ' Job: ' . $job;
        }
    }
}

Upvotes: 4

Related Questions