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?
BTW, I am using Laravel 8, PHP 7.4.13
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.