I'm having a lot of trouble understanding these arrays in php. Here I want to query SQL to get me the value of cash of the user. Then I want to add it to the $position variable that is later sent to the view. I'v tried a lot now, but i get the error message: Notice: Undefined index: cash

// configuration
$id = $_SESSION["id"];
$rows = query("SELECT * FROM `stocks` WHERE $id");
$cash = query("SELECT cash FROM `users` WHERE id = ?", $_SESSION["id"]);

$positions = [];
       $positions[] = ["cash" => $cash["cash"]];

foreach ($rows as $row)
    $stock = lookup($row["symbol"]);
    if ($stock !== false)
        $positions[] = [
            "name" => $stock["name"],
            "price" => $stock["price"],
            "shares" => $row["shares"],
            "symbol" => $row["symbol"],
render("portfolio.php", ["positions" => $positions, "title" => "Portfolio"]);

1 Answer 1


First, after WHERE you should specify column name(s). So this call to query()

$rows = query("SELECT * FROM `stocks` WHERE $id");

should be like that

$rows = query("SELECT * FROM stocks WHERE columnName = ?", $id);

Second, the function query() returns a number of rows, at the first place, where each row is composed of columns. Meanwhile, if you tried to dump() the variable named $cash, you'd find that it's a multi-dimensional array. In order to access the index named cash, you should do something like

$cash[0]["cash"] // access the index named cash in the first row (row[0])

So instead of

$positions[] = ["cash" => $cash["cash"]];

Probably you should have

$positions[] = ["cash" => $cash[0]["cash"]];

Hope that helps!

  • try using DUMP($rows) - it will show the structure and the contents.
    – ihor
    Aug 17, 2016 at 1:00

You must log in to answer this question.

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