1

I am using a recursive function in php. The function travers through an array and inputs some values of the array in a new array. I am using array_push() to enter values in the new array and I have also tried to do it without using array_push. This is the part of the function that calls the recursive function

if ($this->input->post('id') != '') {
    $id = $this->input->post('id');

    global $array_ins;
    $k=0;
    $data['condition_array'] = $this->array_check($id, $menus['parents'], $k);

    // trial
    echo "<pre>";
    print_r($menus['parents']);
    print_r($data['condition_array']);die;
    // trial
}

and this here is the recursive function

function array_check($val, $array_main, $k) {
    // echo $val . "<br>";
    $array_ins[$k] = $val;
    echo $k . "<br>";
    $k++;
    // $array_ins = array_push($array_ins, $val);
    echo "<pre>";
    print_r($array_ins);
    if ($array_main[$val] != '') {
        for ($i = 0; $i < sizeof($array_main[$val]); $i++) {
            $this->array_check($array_main[$val][$i], $array_main, $k);
        }
        // $k++;
    }

I've been trying to fix this erorr for quite some time with no luck . I would really appreciate any help possible . thanks in advance

Zayn Ali
  • 4,055
  • 1
  • 23
  • 37

3 Answers3

2

Move the global $array_ins; statement into the function.

Don
  • 4,245
  • 24
  • 33
1

Pass the variable $array_ins as a parameter to function

function array_check($val, $array_main, $k,$array_ins) {


}

and call the function

$this->array_check($id, $menus['parents'], $k,$array_ins);

or

function array_check($val, $array_main, $k) {

global $array_ins;

}

usage of global is not recommended in php check it here Are global variables in PHP considered bad practice? If so, why?

Arun Kumaresh
  • 5,734
  • 5
  • 28
  • 45
0

The global keyword should be used inside of functions so that the variable will refer to the value in the outer scope.

<?php
$a = 1;
$b = 2;

function Sum()
{
    global $a, $b;

    $b = $a + $b;
} 

Sum();
echo $b; // 3
Ryan Tuosto
  • 1,856
  • 14
  • 22