harpreet kaur
harpreet kaur

Reputation: 141

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

Upvotes: 0

Views: 132

Answers (2)

KV Prajapati
KV Prajapati

Reputation: 94635

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

  }

Upvotes: 1

imm
imm

Reputation: 5919

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
)

Upvotes: 0

Related Questions