hey guys please help me out with this. am trying to write a function that finds every array within and array then modify all arrays found.
I have achieved the first goal, the second not quite.
here is the function so far.
$count = 0;
function findObj($arr) {
global $count;
foreach($arr as $key => $value) {
if(gettype($arr[$key]) == 'array') {
// append the string "here" to the array found
$arr[$key][] = 'here';
$count++;
// call same function within function with the argument of array found
findObj($arr[$key]);
}
}
$rtnArr = [$count, $arr];
return $rtnArr;
}
var_dump(findArr($arr));
// this returns
array (size=5)
0 => int 1
1 => int 44
2 => int 43
3 =>
array (size=2)
0 => string 'hello' (length=5)
1 => string 'here' (length=4)
4 =>
array (size=4)
0 => string 'one' (length=3)
1 => string 'two' (length=3)
2 =>
array (size=2)
0 => string 'three' (length=5)
1 => string 'four' (length=4)
3 => string 'here' (length=4)
only the arrays in the first level where modified. please help my brain is about to explode().
<?php
$input =
[
[
'foo',
[
'bar',
'baz',
[
'bat',
'man'
]
]
]
];
function add_extra_element_recursive(array &$array)
{
foreach($array as $key => &$value) {
if(is_array($value)) {
add_extra_element_recursive($value);
}
}
$array[] = 'extra';
}
var_export($input);
echo "
";
add_extra_element_recursive($input);
var_export($input);
Output:
array (
0 =>
array (
0 => 'foo',
1 =>
array (
0 => 'bar',
1 => 'baz',
2 =>
array (
0 => 'bat',
1 => 'man',
),
),
),
)
array (
0 =>
array (
0 => 'foo',
1 =>
array (
0 => 'bar',
1 => 'baz',
2 =>
array (
0 => 'bat',
1 => 'man',
2 => 'extra',
),
3 => 'extra',
),
2 => 'extra',
),
1 => 'extra',
)