note 93445 deleted from control-structures.foreach by googleguy

From: Date: Wed, 14 Nov 2012 22:27:54 +0000
Subject: note 93445 deleted from control-structures.foreach by googleguy
References: 1  Groups: php.notes 
Request: Send a blank email to php-notes+get-191961@lists.php.net to get a copy of this message
Note Submitter: s dot mattison at gmail dot filtersoutmyspam dot com ---- 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 ?>

« previous php.notes (#191961) next »