note 48182 added to function.array-shift
| From: | JamesMcGuigan at osu1 dot php dot net | Date: | Tue, 14 Dec 2004 19:26:00 +0000 |
| Subject: | note 48182 added to function.array-shift | ||
| Groups: | php.notes | ||
| Request: | Send a blank email to php-notes+get-81793@lists.php.net to get a copy of this message | ||
while(array_shift()) can be used to process multiple arrays and/or database results in a single
loop. The || short circuts and only evaluates the first statement until it runs out of data.
It can help to reduce duplicated code (the rule is code once and once only).
Note that each ($row = ) statement much be encased in ()'s otherwise you will get funny
results. If you use two array_shift($array) statements and forget the ()'s, you will repeatedly
get the first element of the first array for the for the count of the $array.
<?php
require_once('class.db.php');
$sql = "SELECT title FROM links";
$result = mysql_query($sql, $db->connection);
$defaults = array(
array('title' => 'None'),
array('title' => 'Unknown')
);
while ( ($row = mysql_fetch_assoc($result))
|| ($row = array_shift($defaults)))
{
echo $row['title'] . "<br>";
}
?>
This will print out (depending on database contents):
Title1
Title2
Title3
...
None
Unknown
----
Manual Page -- http://www.php.net/manual/en/function.array-shift.php
Edit -- http://master.php.net/manage/user-notes.php?action=edit+48182
Delete -- http://master.php.net/manage/user-notes.php?action=delete+48182&report=yes
Reason: bad code -- http://master.php.net/manage/user-notes.php?action=delete+48182&report=yes&reason=bad+code
Reason: spam -- http://master.php.net/manage/user-notes.php?action=delete+48182&report=yes&reason=spam
Reason: useless example -- http://master.php.net/manage/user-notes.php?action=delete+48182&report=yes&reason=useless+example
Reason: contains commercial links -- http://master.php.net/manage/user-notes.php?action=delete+48182&report=yes&reason=contains+commercial+links
Reason: useless note -- http://master.php.net/manage/user-notes.php?action=delete+48182&report=yes&reason=useless+note
Reject -- http://master.php.net/manage/user-notes.php?action=reject+48182&report=yes
Search -- http://master.php.net/manage/user-notes.php