coder
coder

Reputation: 299

PHP: Define variables / array within a loop

I've got this code

$vote = array(
    $arrayName[0][firstsector],
    $termin[1][firstsector],
    $termin[2][firstsector],
    $termin[3][firstsector]
);

Now I want to create a loop for it. I tried this:

$howMuchIneed = 5;

for ($x = 0; $x <= $howMuchIneed; $x++) {
    $vote = array(
        $arrayName[$x][firstsector]
    );
}

But the result doesn't look the same as the first code.

Upvotes: 0

Views: 66

Answers (2)

Lorenzo Belfanti
Lorenzo Belfanti

Reputation: 1247

Have you tried this ?

for ($x = 0; $x <= $howMuchIneed; $x++) {
    array_push($vote, $arrayName[$x][firstsector]);
}

initializes Array

$vote = array();

If you want to learn more about array_push http://php.net/manual/en/function.array-push.php

Upvotes: 1

Kristian Vitozev
Kristian Vitozev

Reputation: 5971

Try this (in your for loop):

$vote[] = $arrayName[$x]['firstsector'];

... and don't forget to declare your array before your loop!

$vote = array();

And in your first example you have 4 elements, condition in your for should be $x < 4 - arrays in PHP are zero-based.

Upvotes: 0

Related Questions