note 93445 added to control-structures.foreach
| From: | s dot mattison at gmail dot filtersoutmyspam dot com | Date: | Thu, 10 Sep 2009 10:19:16 +0000 |
| Subject: | note 93445 added to control-structures.foreach | ||
| Groups: | php.notes | ||
| Request: | Send a blank email to php-notes+get-160401@lists.php.net to get a copy of this message | ||
I hope other people find this useful.
<?php
/*
---------------------------------
"Null" Array filler
by Steve Mattison
This script shows one way PHP can
display an array, and pad it with
'nonexistant' values. This may be
useful, for instance, in reducing
the size of a database by storing
only values that deviate from a
set standard.
---------------------------------
*/
$arr = array(3, 5, -47); //the values. we're looking for the first two.
//an arbitrary lower number must append the array.
//this is so the main loop continues after the last value has been found.
$arr2 = array("oranges", "pears", null); //value descriptions.
foreach ($arr as $key=>$value) { //get next value that we seek.
for($iterate=$last+1;$iterate<10;$iterate++){ //iterate a loop.
//start at the last position+1, in case we've already looped once.
//if we haven't looped yet, $last is not defined; we start at 1.
$last=$iterate; //keep track of our position.
echo '<br>['.$iterate.'] - '; //show it.
if($iterate==$value){ //an array value has appeared.
echo ($arr2[$key]); //show the deviant value.
break; //break the loop and get the next value.
} //end if
else echo ("apples"); //otherwise show the default value.
} //next $iterate
//array values higher than the loop condition will be ignored.
//optionally, you may wish to check for this and display them here.
} //next-each $arr
unset($value); //clear up the memory used by foreach
//Example Result Set:
//[1] - apples
//[2] - apples
//[3] - oranges
//[4] - apples
//[5] - pears
//[6] - apples
//[7] - apples
//[8] - apples
//[9] - apples
?>
----
Server IP: 208.69.120.35
Probable Submitter: 24.20.145.95
----
Manual Page -- http://www.php.net/manual/en/control-structures.foreach.php
Edit -- https://master.php.net/note/edit/93445
Del: integrated -- https://master.php.net/note/delete/93445/integrated
Del: useless -- https://master.php.net/note/delete/93445/useless
Del: bad code -- https://master.php.net/note/delete/93445/bad+code
Del: spam -- https://master.php.net/note/delete/93445/spam
Del: non-english -- https://master.php.net/note/delete/93445/non-english
Del: in docs -- https://master.php.net/note/delete/93445/in+docs
Del: other reasons-- https://master.php.net/note/delete/93445
Reject -- https://master.php.net/note/reject/93445
Search -- https://master.php.net/manage/user-notes.php