Using array_shift on while loop with fetchAll() on SELECT * from mysql

1.8k views Asked by At

I have a question on understanding how using *array_shift* with a fetchAll on a while loop in this example works? The intended result is just to fetch the data from the db and use it for filling out a CRUD app.

I understand *array_shift* drops off the first result of an array but am not sure why this does not impact the results returned in this example. Just trying to wrap my head around this process.

$pdo = Database::connect();
$sql = $pdo->prepare("SELECT * FROM contacts ORDER BY name ASC");
$sql->execute();
$result = $sql->fetchAll(PDO::FETCH_ASSOC);

$contacts = array();
while ($obj = array_shift($result)) {
    $contacts[] = $obj;
}
return $contacts;
1

There are 1 answers

1
Explosion Pills On BEST ANSWER

array_shift will remove the first element from an array and return it. So if you have an array like

array("one", "two", "three")

Using array_shift will return "one" and the source array will be updated to array("two", "three"). When done in a loop, this means that eventually the source array will be pruned down to array().

According to the documentation, array_shift on an empty array returns NULL. You can think of the code as running:

if ($obj = NULL)

This is falsy, so the statement (while in your case) is not evaluated.