ben ben - 1 year ago 82
PHP Question

Using an array with a key as an array key

I am using arrays with keys as the key to an array, in the code like below,

$team = array();
$counter = 0;

$sql = "SELECT Home, Away, Result, Points FROM schedule";
$schedulequery = mysqli_query($conn, $sql);

// divy out the points
if (mysqli_num_rows($schedulequery) > 0) {
while($teamrow = mysqli_fetch_assoc($schedulequery)) {

$points = $teamrow["Points"];
if ($teamrow["Result"] == "Home"){
$team[$teamrow["Home"]] = $team[$teamrow["Home"]] + $points;
if ($teamrow["Result"] == "Tie"){
$team[$teamrow["Home"]] = $team[$teamrow["Home"]] + ($points/2);
$team[$teamrow["Away"]] = $team[$teamrow["Away"]] + ($points/2);
if ($teamrow["Result"] == "Away"){
$team[$teamrow["Away"]] = $team[$teamrow["Away"]] + $points;
if ($teamrow["Result"] == "HomeForfeit"){
$team[$teamrow["Home"]] = $team[$teamrow["Home"]] - $points;
$team[$teamrow["Away"]] = $team[$teamrow["Away"]] + $points;
if ($teamrow["Result"] == "AwayForfeit"){
$team[$teamrow["Home"]] = $team[$teamrow["Home"]] + $points;
$team[$teamrow["Away"]] = $team[$teamrow["Away"]] - ($points/2);
if ($teamrow["Result"] == "DuelForfeit"){
$team[$teamrow["Home"]] = $team[$teamrow["Home"]] - ($points/2);
$team[$teamrow["Away"]] = $team[$teamrow["Away"]] - ($points/2);

This code is working and successfully updating in my MySql table (that part of the code not included) every time one of these lines is used I get a "PHP Notice: Undefined index: " error.

Is this bad practice or is this the wrong syntax? I am confused why it is working but still tells me undefined index.

The lines that are erroring out are all the times I access a line with a double array like "$team[$teamrow["Home"]]". Any time one of those is accessed I get an error.

EDIT: I think I get it.. I am creating a new key in an array that doesn't already exist?

Answer Source

from what i can tell the problem might be the lines like $team[$teamrow["Home"]] = $team[$teamrow["Home"]] + $points;.

at the start of your code you initialize $team as an empty array with no indexes or values. then in your while loop you have lines like $team[$teamrow["Home"]] = $team[$teamrow["Home"]] + $points; and the problem is the right side of the =. what is the value of $team[$teamrow["Home"]] is being added to $points in the very first iteration (when $team is uspposed to be an empty array)?

since it appears you are using integers, at the start of your while loop i would do the following

    $team[$teamrow["Home"]] = 0;

and likewise i'd do the same with $team[$teamrow["Away"]]. this way if $team[$teamrow["Home"]] is undefined it'll be given a value of 0

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download