Home > Enterprise >  Changing the value of a nested array inside an recursive function
Changing the value of a nested array inside an recursive function

Time:05-02

I have a recursive function in PHP that calculate the total size in bytes the array would take, and I also need to check if there are some value that are greater than 32766 (biggest int), if so, it will set it value to 404

An Example of array that it will receive

[[12,123,145],[[12,123321,543],"hello"],1232456]

For practical reasons, I only pasted the part of the function where I make the verification

function sizePayRecursive($arr,$size){
  foreach ($arr as $key => &$item) {
    if (is_array($item))
    {
      $size = sizePayRecursive($item,$size);
    }
    if (is_int($item))
    {
      if($item > 32766)
      {
        $arr[$key]= 404;
      }
      $size  = 2;
    }
}


Unfortanately, nothing change when I try to do this, how can I do this?

CodePudding user response:

If you want to change your values inside that array in your function, then you can pass a variable by reference to a function so the function can modify the variable.

So you need to change from this:

function sizePayRecursive($arr,$size)

to this:

function sizePayRecursive(&$arr, $size)

To understand it better you can read it more about it here in php documentation

CodePudding user response:

I hope I understood your question correctly. It is checked by selecting string and int in the function below. The wrong ones are passed to the result function. Empty arrays are cleared.

<?php 
function sizePayRecursive($arr,$result=[]){
  foreach ($arr as $key => $item) { //recursive
        if (is_array($item)){
            $result[]=sizePayRecursive($item,@$result[$key]);
        }elseif (is_int($item)){ //integer
            if($item > 32766){
                $result[$key]= 404;
            }
        }elseif (is_string($item)){ //string
            if(strlen($item) > 32766){
                $result[$key]= 404;
            }
        }
    }
    return $result;
}
function array_filter_recursive($input){  //delete empty array 
    foreach ($input as $value){ 
        if (is_array($value)){ 
            $value = array_filter_recursive($value); 
        } 
    } 
    return array_filter($input); 
} 

$data=[[12,123,145],[[12,123321,543],"hello"],1232456];
$final=array_filter_recursive(sizePayRecursive($data));
echo '<pre>';
print_r($final);
?>

result

Array
(
    [1] => Array
        (
            [0] => Array
                (
                    [1] => 404
                )

        )

    [2] => 404
)
  • Related