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
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
)

Link to comment
Share on other sites

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
}

?>

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • 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.