0

Hello i want to return array using php code it doesnot gives any output

Please take a look at code

<?php       
header('Content-Type: text/plain'); 
$a=array();

function showCombinations($string, $traits, $i)
{
    //print_r($i);
    if ($i >= count($traits)) {
        $a[]=trim($string) . "\n";
        return $a;
    } else {
        foreach ($traits[$i] as $trait) {
            //print_r($trait[$i]);
            showCombinations("$string $trait", $traits, $i + 1);
        }
    }
}

$traits = array
(
    array('Happy', 'Sad', 'Angry', 'Hopeful'),
    array('Outgoing', 'Introverted'),
    array('Tall', 'Short', 'Medium'),
    array('Handsome', 'Plain', 'Ugly')
);
//print_r($traits);exit;
echo showCombinations(' ', $traits, 0);
?>
2
  • what output you're expecting? Commented Oct 20, 2011 at 5:29
  • i want to return the same array as it prints in my if statement. Commented Oct 20, 2011 at 5:53

2 Answers 2

1

Read PHP variable scope. Use $GLOBALS[].

function showCombinations($string, $traits, $i)
  {         //print_r($i);
    if ($i >= count($traits))
    {
      $GLOBALS["a"][]=trim($string) . "\n";
      return $a;
    }
    else
    {
      foreach ($traits[$i] as $trait)
      //print_r($trait[$i]);
      showCombinations("$string $trait", $traits, $i + 1);  
    }

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

Comments

0

in your else part, you need to write:

return showCombinations("$string $trait", $traits, $i + 1);

your code then outputs:

Array

use print_r instead to see the contents of the array:

print_r(showCombinations(' ', $traits, 0));

outputs the following:

Array
(
  [0] => Happy Outgoing Tall Handsome
)

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.