I am trying to get values out of an indexed array, but when I use a variable as the index (which is equal to an index in the array), it does not appear. I get an Undefined Index
Error. Why is this happening? Does anyone know? Thanks!
I have the following code:
$bookarray = array();
$books = mysqli_query($db, "SELECT * FROM books");
while($row = mysqli_fetch_assoc($books)){
$bookarray[$row['bookID']] = array(
'title' => $row['title'],
'author' => $row['author'],
'price' => $row['price']
);
}
echo"<hr>";
print_r($bookarray);
echo"<hr>";
echo $bookarray[5]['title']."<br />";
foreach($_SESSION['cart'] as $cartedbook){
echo $cartedbook;
echo $bookarray[$cartedbook]['title'];
echo "<br />";
}
This is the output:
Array
(
[1] => Array
(
[title] => Java 2 for Pro Deelopers
[author] => Michael Morgan
[price] => 34.99
)
[2] => Array
(
[title] => Installing XAMPP
[author] => Thomas Down
[price] => 24.99
)
[3] => Array
(
[title] => Alice Through the Looking Glass
[author] => Louis Carroll
[price] => 72.35
)
[4] => Array
(
[title] => Quantum Mechanics in 124 Hours
[author] => Neils Bohr
[price] => 24.99
)
[5] => Array
(
[title] => PHP For Fun And Profit
[author] => Thomas Shenk
[price] => 49.99
)
[28] => Array
(
[title] => Test
[author] => Eric Gross
[price] => 100.00
)
)
3
Notice: Undefined index:
3 in C:\xampp\htdocs\FinalProject\cart.php on line 52
Title Author Price
If I look at the source of your question, it seems there is a newline character before the number (so, it would be "\n5"
instead of 5
, which logically cannot be found), can you confirm this? What does a var_dump($cartedbook);
yield?