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

1
  • please post sample values from $array_ins Commented Aug 4, 2017 at 5:09

3 Answers 3

2

Move the global $array_ins; statement into the function.

Sign up to request clarification or add additional context in comments.

Comments

2

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?

1 Comment

$array_ins should be passed by reference, I suppose.
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

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.