8

I have an array like this and the code using foreach loop.

$arr = array( array ( array( 'CAR_TIR', 'Tires', 100 ),
           array( 'CAR_OIL', 'Oil', 10 ),
           array( 'CAR_SPK', 'Spark Plugs', 4 )
          ),
       array ( array( 'VAN_TIR', 'Tires', 120 ),
           array( 'VAN_OIL', 'Oil', 12 ),
           array( 'VAN_SPK', 'Spark Plugs', 5 )
          ),
       array ( array( 'TRK_TIR', 'Tires', 150 ),
           array( 'TRK_OIL', 'Oil', 15 ),
           array( 'TRK_SPK', 'Spark Plugs', 6 )
          )
      );


function recarray($array)
{
    foreach($array as $key=>$value)
    {
        if(is_array($value))
        {
            RecArray($value);
        }
        else
        {
            echo "key = $key value = $value";
       }
    }
}
recarray($arr);

I have to traverse the array using recursion and without using foreach.

3
  • 3
    without using foreach - why? foreach is kind and a gentle lover... This smells of homework to me, if it is please tag it as such.
    – DaveRandom
    Jul 18, 2012 at 9:47
  • yeah its kind a home work. Thanks alot
    – ejaz
    Jul 18, 2012 at 10:07
  • Also, traversing arrays with foreach is not resource-efficient when you don't really need to get all values from each position of the array, or you just want to delete items from the child array.
    – andreszs
    Aug 23, 2017 at 0:18

3 Answers 3

7

Simple depth first search:

function DFS($array) {      
    for ($i = 0; $i < count($array); $i ++) {
        if (is_array($array[$i])) {
            DFS($array[$i]);
        }
        else {
            echo "key: ".$i.", value: ".$array[$i]."<br />";
        }
    }
}
1
  • 3
    FYI: for($i = 0; $i < count($array); $i++)... means that the count() function will be fired for EVERY iteration of $array. Better to do this: $arrayCount = count($array); for($i = 0; $i < $arrayCount; $i++)...
    – macinnir
    Jun 5, 2015 at 4:11
2

What about array_walk_recursive()? it can apply function to each element of the array:

function test_print($value, $key)
{
    echo "key = $key value = $value";
}

array_walk_recursive($arr, 'test_print');

not tested

0

I would use a while loop - like

while($i < count($array)) {}
1
  • 1
    there's no .length property in php
    – Teneff
    Jul 18, 2012 at 9:52

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.