Tinabot
Tinabot

Reputation: 429

PHP recursive multidimensional loop

$printArr = recursive($newArray); //calls recursive function
$data = [];
var_dump($data);
var_dump($printArr);
    function recursive($array, $level = 0)
    {
        $searchingValue = 'tableName';
        foreach($array as $key => $value)
        {
                //If $value is an array.
                if(is_array($value))
                {
                    recursive($value, $level + 1);
                } 
                else
                {
                    //It is not an array, so print it out.
                    if($key == $searchingValue)
                    {
                        echo "[".$key . "] => " . $value, '<br>';
                        $data[] = $value;
                    }
                }
        }
    }

So I have this function and I am trying to save $value value into $data[] array. But it always returns it empty and I don't know why I can't get $value saved outside the function. If i echo $value I get what i need but like I've mentioned the variables doesn't get saved in this case - table names.

Upvotes: 6

Views: 2512

Answers (2)

Eakethet
Eakethet

Reputation: 682

You can't access variable $data, which is outside the function, from the function. You need to pass it by reference or return it. Small example

<?php

$a = 1;

// Your case
function b() {
    $a = 4;
    return true;
}
// Passing by reference
function c(&$d) {
    $d = 5;
    return true;
}
// Using return
function d($d) {
    $d = 6;
    return $d;
}

b();
var_dump($a);

c($a);
var_dump($a);

$a = d($a);
var_dump($a);

https://3v4l.org/UXFdR

Upvotes: 0

Praveen S
Praveen S

Reputation: 395

You need to pass the $data to your recursive function. Also you need to return the $data.

Try this code :

function recursive($array, $level = 0, $data =[])
{
    $searchingValue = 'tableName';
    foreach($array as $key => $value)
    {
            //If $value is an array.
            if(is_array($value))
            {
                recursive($value, $level + 1 , $data);
            } 
            else
            {
                //It is not an array, so print it out.
                if($key == $searchingValue)
                {
                    echo "[".$key . "] => " . $value, '<br>';
                    $data[] = $value;
                }
            }
    }
    return $data;
}

Upvotes: 6

Related Questions