Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

array_unshift() expects parameter 1 to be array, null given

I want to add data to my array using array_unshift() but it
shows " array_unshift() expects parameter 1 to be array, null given "

here is my code:

public function index($child = null)
{
    $crumbs = [];

    function getParents($id){
        $parent = Instrument::where('id', $id)->first(['id', 'title', 'parent']);

        if($parent->parent != null){
            array_unshift($crumbs, $parent);
            getParents($parent->parent);
        }
    }

    if($child != null){ 
        getParents($child);
    }
    
    //return code here
}

do you have any solution?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

BTW, I am using Laravel 8, PHP 7.4.13

>Solution :

Variable $crumbs isn’t visible in getParents function.

So you should pass it as an argument or make it a global variable or make a property for an object.

public function index($child = null)
{
    $crumbs = [];

    function getParents($id, &$crumbs){
        $parent = Instrument::where('id', $id)->first(['id', 'title', 'parent']);

        if($parent->parent != null){
            array_unshift($crumbs, $parent);
            getParents($parent->parent);
        }
    }

    if($child != null){
        getParents($child, $crumbs);
    }

    //return code here
}

For example like this.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading