0

I am trying to solve this problem to learn logic formulations, but this one's really taken too much of my time already.

Rules are simple, No loops and no built in PHP functions (eg. print_r, is_array.. etc).

This is what I have come up with so far.

function displayArray(array $inputArray, $ctr = 0, $tempArray = array()) {
//check if array is equal to temparray
if($inputArray != $tempArray) {

    // check if key is not empty and checks if they are not equal
    if($inputArray[$ctr]) {
        // set current $tempArray key equal to $inputArray's corresponding key
        $tempArray[$ctr] = $inputArray[$ctr];

        if($tempArray[$ctr] == $inputArray[$ctr]) { 
            echo $tempArray[$ctr];]
        }

        $ctr++;
        displayArray($inputArray, $ctr);
    }
}
}

This program outputs this:

blackgreen

The problem starts when it reaches the element that is an array

$array = array(
    'black',
    'green',
    array(
        'purple',
        'orange'
    )
);

displayArray($array);

Any tips?

This what the return value is supposed to be: blackgreenpurpleorange

  • Third value in your $array is another array and first two values are simple strings. How that can be possible? So you want to check for arrays – arunrc Aug 23 '14 at 06:57
  • What is the `$tempArray` argument for? Why aren't you passing this argument when you do the recursive call? – Barmar Aug 23 '14 at 06:58
  • It's there to validate if its not equal to the `$inputArray`. If it's not equal, it will keep putting key values from `$inputArray` to itself with the help of `ctr`, which makes it equal at the end of the recursion. I hope that make sense. @arunrc Yes. That's exactly what i want to do. – user3530303 Aug 23 '14 at 07:04
  • It will never be equal to `$inputArray`. – Barmar Aug 23 '14 at 07:08
  • @Barmar So far it does go equal in the end if it's compared to a single-dimensional array.. What do you have in mind though? – user3530303 Aug 23 '14 at 07:10
  • 1
    You need to use `is_array()` to test whether an element is an array. If so, you need to call your function recursively on `$inputArray[$ctr]`. – Barmar Aug 23 '14 at 07:10
  • possible duplicate of [Implode data from a multi-dimensional array](http://stackoverflow.com/questions/16710800/implode-data-from-a-multi-dimensional-array) – MC_delta_T Aug 23 '14 at 07:10
  • How will it ever be equal? You never pass that argument when you call the function, so it always uses the default value, which means it creates a new array each time. – Barmar Aug 23 '14 at 07:11
  • To test when to stop, you should test whether `$ctr >= count($inputArray)`. – Barmar Aug 23 '14 at 07:12
  • @Barma see my complete solution below – saurav Aug 23 '14 at 07:13
  • @Barmar I see what you mean now, error reporting was turned off. Didn't notice. Indeed, it's outputting multiple arrays when I use vardump. I'll analyze what you stated. Thanks – user3530303 Aug 23 '14 at 07:29
  • 1
    Actually, this question shows how people are NOT READING the OP requirements and start to dump some random things. Just saying. – kodeart Aug 23 '14 at 08:00

4 Answers4

-2

What about this? You must check if it is array or not.

function display_array(&$array, $index=0) {
  if (count($array)<=$index) return;
  if (is_array($array[$index])) {
    echo '[ ';
    display_array($array[$index]);
    echo '] ';
  }  
  else         
    echo "'" . $array[$index] . "' ";

  display_array($array, $index+1);
}

// Try:
// $a = ['black', 'green', ['purple', 'orange'], 'beer', ['purple', ['purple', 'orange']]];
// display_array($a);
// Output:
// 'black' 'green' [ 'purple' 'orange' ] 'beer' [ 'purple' [ 'purple' 'orange' ] ]
marek094
  • 424
  • 2
  • 11
-2

try this have to use some inbuilt function like isset and is_array but its a complete working recursive method without using loop.

function displayArray(array $inputArray, $ctr = 0) {
    if(isset($inputArray[$ctr]))
    {   
        if(is_array($inputArray[$ctr]))
        {
            return displayArray($inputArray[$ctr]);
        }
        else
        {
            echo $inputArray[$ctr];
        }   
    }
    else
    {
        return;
    }
    $ctr++;
    displayArray($inputArray, $ctr);
}

$array = array(
    'black',
    'green',
    array(
        'purple',
        'orange'
    )
);

displayArray($array);

OUTPUT :

blackgreenpurpleorange

DEMO

Satish Sharma
  • 9,547
  • 6
  • 29
  • 51
-2

This was fun. I decided to make it work with most data types while I was at it. Just don't throw it any objects or nulls and things should work.

No more @ error suppression. Now returns the string instead of echoing it.

I realized too late that isset() is actually a language construct rather than a function, and went with a null termination strategy to determine the end of the arrays.

function concatinateRecursive($array, $i = 0) {
    static $s = '';
    static $depth = 0;
    if ($i == 0) $depth++;

    // We reached the end of this array.
    if ($array === NULL) {
        $depth--;
        return true;
    }

    if ($array === array()) return false; // empty array
    if ($array === '')      return false; // empty string
    if (
        $array === (int)$array   ||      // int
        $array === (float)$array ||      // float
        $array === true          ||      // true
        $array === false         ||      // false
        $array === "0"           ||      // "0"
        $array ==  "1"           ||      // "1" "1.0" etc.
        (float)$array > 1        ||      // > "1.0"
        (int)$array !== 1                // string
       )
    {
        $s .= "$array";
        return false;
    }

    // Else we've got an array. Or at least something we can treat like one. I hope.
    $array[] = NULL; // null terminate the array.
    if (!concatinateRecursive($array[$i], 0, $s)) {
        $depth--;
        return concatinateRecursive($array, ++$i, $s);
    }
    if ($depth == 1) {
        return $s;
    }
}

$array = array(
    'black',
    'green',
    array(
        'purple',
        'orange'
    )
);

echo concatinateRecursive($array);

blackgreenpurpleorange

Live demo

Community
  • 1
  • 1
user3942918
  • 25,539
  • 11
  • 55
  • 67
  • Hmm.. Man, you are the first person who probably did it in 2014. What debugger do use? EDIT: I removed the @ and it shows that it doesn't work the way it should. – user3530303 Aug 23 '14 at 09:15
  • Why do you need the `$test` variable? Can't you just do `if ($array === [])`? – Shoe Aug 23 '14 at 09:17
  • Well.. @ in front of the function covers up the warnings and errors. And, the function must return blackgreenpurpleorange, not echo them one by one. Using this on assert() function provides additional errors. – user3530303 Aug 23 '14 at 09:52
  • Sorry about that. Expecting output from functions/methods usually mean having a final and definite return value. Again, sorry for assuming. – user3530303 Aug 23 '14 at 12:13
-3

complete answer

$myarray = array(
    'black',
    'green',
    array(
        'purple',
        'orange'
    )
);

function printAll($a) {
    if (!is_array($a)) {
        echo $a, ' ';
        return;
    }

    foreach($a as $k => $value) {
         if($k<10){
             //printAll($k);
             printAll($value);
        }
    }
}


printAll($myarray);
saurav
  • 487
  • 1
  • 7
  • 21
  • 1
    `is_array` is a builtin function. – Shoe Aug 23 '14 at 07:12
  • 1
    @jeffery whats problem with that in place of array u can just romove array cheking step and reloop – saurav Aug 23 '14 at 07:19
  • @saurav The problem is that if you "just romove array checking" then you are not able to distinguish between elements and the array itself thus leading to a [malformed output](http://ideone.com/YbYhcT). – Shoe Aug 23 '14 at 07:23