1

Currently working through pset7 (Finance) and can't seem to wrap my head around how this piece of code works:

$positions = [];
//iterate through rows
foreach ($rows as $row)
{
    $stock = lookup($row["symbol"]);
    if ($stock !== false)
    {
        $positions[] = [
            "name" => $stock["name"],
            "price" => $stock["price"],
            "shares" => $row["shares"],
            "symbol" => $row["symbol"]
        ];
    }
}

Through every iteration through rows, wouldn't $positions["shares"] and $positions["symbol"] get over written by the new values from $row["shares"] and $row["symbol"]? How is $positions able to store all the rows of $rows?

1

Each $row[] is stored as an associative array. $positions[] is an array of arrays. The values in each row do not overlap, because they are stored in adjacent arrays.

EDIT:

The code does iterate through $positions, in a way. More precisely, the code iterates through the $rows returned by the database query using foreach ($rows as $row).

For each row, it passes the value of $row["symbol"] as an argument to the lookup() function and returns the associative array $stock.

Then it uses some values from $row and some values from $stock to create a new indexed array called $positions, which it builds up row by row (or position by position).

These keys and values will be needed later in order to pass data to render(portfolio.php). Get it?

By the way, if this answers your question, be sure to accept it by clicking the green check mark. Otherwise, it will haunt the forums forever as a zombie unanswered question.

2
  • 1
    I took a look at dump($positions) and noticed how $positions[0] is an array, and $positions[1] is another array. But the code doesn't iterate through $positions when storing the values, how does it know to advance the position from $positions[0] to $positions[1]? – Chris Shi Aug 19 '16 at 18:29
  • 1
    I think I get it. Thanks for the quick reply! – Chris Shi Aug 19 '16 at 20:15

You must log in to answer this question.

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