Reputation: 28384
I have the following code:
$id = $_GET['id'];
echo '<br>' . 'id: ' . $id . '<br><br>';
echo '<pre>';
print_r($itemQtys);
echo '</pre>';
echo '<br>' . 'itemqtys[id]: ' . $itemQtys[$id] . '<br>';
echo '<br>' . 'id: ' . $id . '<br>';
The output is:
id: 5
Array
(
[5] => 12
)itemqtys[id]:
id: 5
As you can see, when I try to access the value in the array using the $id variable as the key, no value is returned. However, when I do this:
echo '<br>' . 'itemqtys[5]: ' . $itemQtys[5] . '<br>';
The result is:
itemqtys[5]: 12
Why can't I use a variable to specify the index in the array?
Upvotes: 2
Views: 1879
Reputation: 9957
$id
probably does not contain what you expect, cast it to an integer first.
Change your first line to:
$id = (int) $_GET['id']
;
$_GET['id']
returns a string and you have to cast it to int
before using it as an array index.
Upvotes: 1
Reputation: 31813
when debugging use var_dump() to inspect values. Notice var dump tells you the string length. right click > view html source when debugging too.
My guess is that $id is a string and has trailing whitespace characters.
Upvotes: 6