3

I am new to Laravel and trying to pass a one dimensional array from controller to the view.

This is my controller function

 public function onedim_array()
    {
        $info = array(
            'firstname' => 'John',
            'lastname' => 'Cena',
            'from' => 'USA'
            );

        return view('one_dim_array',  compact('info'));
    }

This is my view file:

<?php

foreach($info as $i)
{
    echo $i['firstname'];
}

?>

It gives me the following error:

ErrorException in 34a7177cfbceee0b4760125499bdaca34b567c0b.php line 5: Illegal string offset 'firstname' (View: C:\AppServ\www\blog4\resources\views\one_dim_array.blade.php)

I don't know where I am making mistake. Please Help

3 Answers 3

7

Since it's not multidimensional array, use this instead of foreach():

$info['firstname']
Sign up to request clarification or add additional context in comments.

Comments

0

foreach() allow you to traverse all items in your array. And in your code snippet

<?php

foreach($info as $i)
{
    echo $i['firstname'];
}

?>

you try to get element with index 'firstname' from a string (in your example it will be 'John'). If you want traverse all elements and display them, try this:

foreach($info as $i)
{
    echo $i;
}

or if you want to display specific element of your array, try this

echo $info['firstname'];

or

echo $info['lastname'];

Comments

0

I think you're expecting to accept multidimensional array to the view. I think here's the value of the array you're expecting to pass to the view

Controller code:

public function onedim_array()
{
    $info = array(
        array(
            'firstname' => 'John',
            'lastname' => 'Cena',
            'from' => 'USA'
        ),
        array(
            'firstname' => 'John',
            'lastname' => 'Doe',
            'from' => 'Canada'
        ),
    );

    return view('one_dim_array',  compact('info'));
}

PS. Suggestion before diving to study a framework: "Master the basics of PHP first", and learn how to debug.

Comments

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.