2

I am doing a small calculator, that has randomly selected sequence of 3 chars (-, / and \).

How can I combine my three arrays into one? I'm using array_merge, but it creates an array that nests 3 arrays in it. How can I make this array one-dimensional?

My code (feedback welcome):

$_SESSION["sekvenssi"] = 15; //sekvenssi means "sequence" in Finnish.

$maara1 = rand(1, $sekvenssi/2);  //Maara means "amount"
$maara2 = rand(1, $sekvenssi/2);

$kenot = array_fill(0, $maara1, "/");
$vastakenot = array_fill(count($kenot), $maara2, "\\");
$tayte = array_fill(
    count($kenot)+count($vastakenot),
    $_SESSION["sekvenssi"]-$maara1-$maara2,
    "-"
);

$kaava = array_merge(array($tayte), array($kenot), array($vastakenot));
shuffle($kaava);

print "<p style='font-family: Courier;font-size: 18px;'>";
    foreach ($kaava as $komponentit) {
    print $komponentit;
}
print "</p>";

So this outputs "ArrayArrayArray", but I want it to produce one array with only one level (now it has 2 levels and thus cannot be printed).

Incognito
  • 20,537
  • 15
  • 80
  • 120
Sampsa
  • 701
  • 1
  • 5
  • 18
  • Well, one "best practice" would be not to post code to an English-speaking forum where there are non-English variable names. :) – Zecc Feb 20 '12 at 14:02
  • @BenLee I'd argue it's slightly different, as he seems to have a handfull of differences such as assumptions he can't print a 2-d array, he's merging three arrays rather than flattening one, etc... – Incognito Feb 20 '12 at 14:09
  • Sorry about that, next time I'll do better :) – Sampsa Feb 20 '12 at 14:10
  • In the meantime people have already given answers, so I won't repeat what they've said, but for the record the term you were looking for is "flatten the array". See for example [question 526556](http://stackoverflow.com/questions/526556/) – Zecc Feb 20 '12 at 14:10

2 Answers2

1

You have already created the array's when you use array_fill, so when you merge them, you are then creating another set of arrays with each array.

Try changing this:

$kaava = array_merge(array($tayte), array($kenot), array($vastakenot));

to

$kaava = array_merge($tayte, $kenot, $vastakenot);
BenOfTheNorth
  • 2,904
  • 1
  • 20
  • 46
  • Thank you alot! That did it! I just love this community, I got an answer in about 3 minutes. – Sampsa Feb 20 '12 at 14:02
0

change

$kaava = array_merge(array($tayte), array($kenot), array($vastakenot));

to

$kaava = array_merge($tayte, $kenot, $vastakenot);

you can use print_r() or var_dump() to test-output variables in php. it will even correctly display arrays and objects.

Basti
  • 3,998
  • 1
  • 18
  • 21