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;
array_shift
will remove the first element from an array and return it. So if you have an array likeUsing
array_shift
will return"one"
and the source array will be updated toarray("two", "three")
. When done in a loop, this means that eventually the source array will be pruned down toarray()
.According to the documentation,
array_shift
on an empty array returnsNULL
. You can think of the code as running:This is falsy, so the statement (
while
in your case) is not evaluated.