linux1880 Posted August 17, 2011 Share Posted August 17, 2011 I have the code below. I would like to insert value in the middle of array without losing any value or original arrays that are comeing from db tables. For example i want to put adverts after 3rd row. How do i achieve it pls help <table width="95%" border="0" cellspacing="0" cellpadding="0" class="programs"> <?php foreach($albums as $k => $v){ echo $v['title'].'-'.$v['description'].'<br/>'; } ?> </table> Quote Link to comment Share on other sites More sharing options...
Psycho Posted August 17, 2011 Share Posted August 17, 2011 I'm not sure what the code above is supposed to illustrate with regards to your request. But, here is a simple function that would allow you to insert a new value into an array at a specified position. You can use positive values to determine position from beginning of array or negative values to determine position from end of array function array_insert(&$array, $newValue, $index) { $index = (int) $index; $array = array_merge( array_slice($array, 0, $index), (array) $newValue, array_slice($array, $index) ); } Usage: $test = array('one', 'two', 'three'); echo "Before:<br>\n"; print_r($test); array_insert($test, 'foo', 1); echo "After:<br>\n"; print_r($test); Output Before: Array ( [0] => one [1] => two [2] => three ) After: Array ( [0] => one [1] => foo [2] => two [3] => three ) Quote Link to comment Share on other sites More sharing options...
xyph Posted August 17, 2011 Share Posted August 17, 2011 He's wondering how, while looping through an array, you can insert a value every 3rd row. I'd achieve this using the modulus operator (returns the remainder of a value) <?php // Populate a dummy array $array = range( 1,30 ); // Here's the code you want $i = 1; // This will count how many values have been echo'd foreach( $array as $k => $v ) { // Loop through array echo $k.' -> '.$v.'<br>'; // Echo array value if( $i % 3 == 0 ) // Check to see if $i is divided evenly by 3 echo 'Third row ad<br>'; // If so, echo the ad $i++; // Increase $i by 1 } ?> Quote Link to comment Share on other sites More sharing options...
linux1880 Posted August 18, 2011 Author Share Posted August 18, 2011 Thank you both mjdamato and xyph Quote Link to comment 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.