Jump to content

pushing values in middle of php array


linux1880

Recommended Posts

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>

Link to comment
https://forums.phpfreaks.com/topic/245046-pushing-values-in-middle-of-php-array/
Share on other sites

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
)

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
}

?>

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.