1

In pset7, I have had a lot of problems regarding the undefined index error. I have been able to fix all of them except this one, and trying to fix it has been making me wonder what that error is. Could you explain what "undefined index" is and what I could do to fix this error in sell.php?

I am getting an undefined index error On my sell.php template on line 10 for "symbol":

$rows = query("SELECT * FROM Stock WHERE id = ?", $_SESSION["id"]);

$stocks[]= [];
foreach ($rows as $row)
{
    $stocks[] = ["symbol" => $row["symbol"],
                 "shares" => $row["shares"]
                ];
}
1
  • Linking to your github repository is a violation of the honor code. Please stick to sharing smaller snippets of code in public. Since you referred to line 10, I took the liberty of pulling out a snippet around that line for your post. If you think a different section would better illustrate your problem, feel free to edit your post with a different snippet.
    – Air
    Aug 7 '14 at 21:53
1

From the excellent resource post on Stack Overflow, Reference: What does this error mean in PHP?:

Notice: Undefined Index

Happens when you try to access an array by a key that does not exist in the array.

A typical example for an Undefined Index notice would be (demo)

$data = array('foo' => '42', 'bar');
echo $data['spinach'];
echo $data[1];

Both spinach and 1 do not exist in the array, causing an E_NOTICE to be triggered.

The solution is to make sure the index or offset does exist, either by using array_key_exists or isset prior to accessing that index.

The full explanation continues at: https://stackoverflow.com/a/12770836/2359271

2
  • How would I fix this using those functions? On the drop-down menu my stocks are showing up, but as the option after the undefined index. Would I just add an if(isset($var)) into the template?
    – sousheel
    Aug 8 '14 at 5:12
  • @user1723 Basically, yes. You can use these functions as the condition of an if statement and only execute the lines of code that try to access that key when you know the key exists; otherwise, do something else.
    – Air
    Aug 8 '14 at 15:18

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .