Jump to content

Array increment by 1 help


extrovertive

Recommended Posts

<?php

$data = array(1, 2, 
"cool"=>7,
7=>3,
"e"=>array(3,5,7), 
"blah"=>3,
array(2,4,6)
);


pr($data);
incrementOne($data);
pr($data);


function incrementOne(&$arr)
{
foreach($arr as $key=>$val)
{
	if(is_array($val)) incrementOne($val);
	else{
		$arr[$key] = $val + 1;
	}	
}
}

function pr($arr)
{
echo '<pre>';
print_r($arr);
echo '</pre>';
}

?>

 

Based on that code above, I get,

Array
(
    [0] => 1
    [1] => 2
    [cool] => 7
    [7] => 3
    [e] => Array
        (
            [0] => 3
            [1] => 5
            [2] => 7
        )

    [blah] => 3
    [8] => Array
        (
            [0] => 2
            [1] => 4
            [2] => 6
        )

)

Array
(
    [0] => 2
    [1] => 3
    [cool] => 8
    [7] => 4
    [e] => Array
        (
            [0] => 3
            [1] => 5
            [2] => 7
        )

    [blah] => 4
    [8] => Array
        (
            [0] => 2
            [1] => 4
            [2] => 6
        )

)

 

The subarrays "e" and 8, I dont get why they dont increment?

Link to comment
https://forums.phpfreaks.com/topic/72170-array-increment-by-1-help/
Share on other sites

You're rather re-inventing the wheel. Try using the array_walk_recursive() function which is specifically for applying a function to every member of a multi dimensional array. Try:

 

<?php
$data = array(1, 2, 
"cool"=>7,
7=>3,
"e"=>array(3,5,7), 
"blah"=>3,
array(2,4,6)
);
function increment(&$v){
echo $v++;
}
function pr($arr)
{
echo '<pre>';
print_r($arr);
echo '</pre>';
}
pr($data);
array_walk_recursive($data,'increment');
pr($data);
?>

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.