letsplay14me
letsplay14me

Reputation: 59

How to I increment a single element in an array?

I have the PHP code below:

<?php

    $length = $_GET["length"];
    $maxValue = $_GET["maxValue"];
    $distribution = array();

    for($j = 0; $j < $maxValue; $j++) {
        $distribution[j] = 5;
    }

    $x = 0;
    $x++;

    for($j = 0; $j < $maxValue; $j++) {
        echo $distribution[j] , " ";
    }

    echo $x;

?>

$x starts as 0 and is incremented by 1. However, just below $x is incremented, I am also incrementing the first element of the "distribution" array - $distribution[0]. And it's not working. It worked fine when I was initializing the elements (set them to 5).

Any ideas on why it might now be working? I am probably referencing the array element wrong. But this seems inconsistent.

Upvotes: 0

Views: 77

Answers (1)

rm-vanda
rm-vanda

Reputation: 3158

When you say $distribution[j] -> php doesn't understand the j as a variable - but rather as an undefined constant

It looks like you are trying to say $distribution[$j] - which is partially -why your increments aren't working - -

The other reason would be that you aren't ever calling $distribution[$j]++ --- so there is no incrementation happening...

Upvotes: 3

Related Questions