I want to create some input fields from an array. I have an array like
$info = array("one" => "one1", "two" => "two2", "three" => "three3" ); foreach ($info as $key => $value){ $field.= "<div class='formcol form-left middle'> \n"; $field.= " <input type='text' id='".$key."' size='12' name='".$key."' style='width:".$tam."px;'/>\n"; $field.= "\t\t\t <div class='text'>".$value."</div>\n"; $field.= "\t\t </div> \n"; } And it does its job very nice, however If the size of array is 6 like
$info = array( "one" => "one1", "two" => "two2", "three" => "three3", "four" => "four4", "five" => "five5", "six" => "six6" ); I woul like to change the code I have to create first 3 values of array to create a "div" and then create other "div" with last 3 values, I will have always mod 3 = 0 values, but the problem is to create a new div every 3 used values
How to improve the code? I was thinking something like
$size = sizeof($info); foreach ($info as $key => $value){ //if ($size % 3 ==0) $field.= "<div class='formcol form-left middle'> \n"; //else // { $field.= " <input type='text' id='".$key."' size='12' name='".$key."' style='width:".$tam."px;'/>\n"; $field.= "\t\t\t <div class='text'>".$value."</div>\n"; // } //if ($size % 3 ==0) $field.= "\t\t </div> \n"; } so for 0,1,2 it is a new div, then for 3,4,5 is new div etc. Is it a best aproach to do this?
$size % 3 == 0outside the loop (just store it in a variable) to reduce repeated code and, less importantly, save a tiny bit of time.I woul like to change the code I have to create first 3 values of array to create a "div" and then create other "div" with last 3 valuesthen finally you create 6 divs, why you need % 3 ?