-Karl- Posted November 1, 2012 Share Posted November 1, 2012 (edited) Hello, I need a more efficient way of alternating an array in order to display them left and right. At the moment I have my HTML: <div class="left"> //This floats everything within the div to the left //Echo buildLeft </div> <div class="right"> //This floats everything within the div to the right //Echo buildRight </div> Then I have the following PHP code in order to take the current array, which is all the results and manipulate it: function buildLeft($array) { $new_array = array(); $i = 0; $count = count($array); while($i < $count) { $new_array[] = $array[$i]; $i = $i+2; } return $new_array; } function buildRight($array) { $new_array = array(); $i = 1; $count = count($array); while($i < $count) { $new_array[] = $array[$i]; $i = $i+2; } return $new_array; } The code works fine and does what I need it to do, but I just don't think it's very efficient, especially when the beginning array could be quite large, then I'm running it through both of these functions. Any ideas? Edited November 1, 2012 by -Karl- Quote Link to comment https://forums.phpfreaks.com/topic/270161-alternating-array-between-left-and-right/ Share on other sites More sharing options...
ManiacDan Posted November 1, 2012 Share Posted November 1, 2012 You could run through the array once: $left = array(); $right = array(); $l = true; foreach ( $arr as $val ) { if ( $l ) { $left[] = $val; } else { $right[] = $val; } $l = !$l; } Quote Link to comment https://forums.phpfreaks.com/topic/270161-alternating-array-between-left-and-right/#findComment-1389292 Share on other sites More sharing options...
-Karl- Posted November 1, 2012 Author Share Posted November 1, 2012 (edited) You could run through the array once: $left = array(); $right = array(); $l = true; foreach ( $arr as $val ) { if ( $l ) { $left[] = $val; } else { $right[] = $val; } $l = !$l; } Hmm, but how would I return it from the function? Edited November 1, 2012 by -Karl- Quote Link to comment https://forums.phpfreaks.com/topic/270161-alternating-array-between-left-and-right/#findComment-1389295 Share on other sites More sharing options...
-Karl- Posted November 1, 2012 Author Share Posted November 1, 2012 Nevermind, fixed it myself: function buildPosts($array) { $new_array = array('left' => array(), 'right' => array()); $i = 0; foreach($array as $val) { if($i == 0) { $new_array['left'][] = $val; $i = 1; } else { $new_array['right'][] = $val; $i = 0; } } return $new_array; } Thanks for the advice though guys! Quote Link to comment https://forums.phpfreaks.com/topic/270161-alternating-array-between-left-and-right/#findComment-1389305 Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.