1

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:

Books


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
    )

)


PHP For Fun And Profit
5
Notice: Undefined index: 5 in C:\xampp\htdocs\FinalProject\cart.php on line 52


3
Notice: Undefined index: 3 in C:\xampp\htdocs\FinalProject\cart.php on line 52

Title     Author     Price

EGr
  • 2,072
  • 10
  • 41
  • 61

2 Answers2

1

Results from mysql queries are strings, even if they are integers in the database. This causes your $bookarray to be associated by numeric strings instead of numeric indexes, which your probably trying to use against it.

Try casting that ID as an int:

$bookarray[(int) $row['bookID']] = array(
SamT
  • 10,374
  • 2
  • 31
  • 39
0

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?

Wrikken
  • 69,272
  • 8
  • 97
  • 136
  • This is the output: `5string(27) " 5"` `3string(27) " 3"` It does look like there is some type of character there... EDIT: I found the error, i did have a newline on another .php file that added the values to the array. Thanks! – EGr Jun 05 '11 at 01:22