Search code examples
phparraysrecursion

Array return in PHP


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);
?>

Solution

  • 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);  
        }
    
      }