Given an array of arrays, how can I cut the substring "GB" from each value?

Each element in my array is an array of approximately 5 values. Some of them numerically end in GB. I need the same array, but with "GB", remote, so that only a number remains.

So, I need to iterate over the entire array, on each subarray take each value and cut the string "GB" from it and create a new array from the output.

Is there an effective way to do this?

+3
source share
4 answers

You can use array_walk_recursive()for this:

array_walk_recursive($arr, 'strip_text', 'GB');

function strip_text(&$value, $key, $string) {
  $value = str_replace($string, '', $value);
}

, ().

+2

, , GB, , . array_map

+1
$arr = ...

foreach( $arr as $k => $inner ) {
   foreach( $inner as $kk => &$vv ) {
      $vv = str_replace( 'GB', '', $vv );
   }
}

This actually keeps the original arrays intact with newlines. (note &$vvthat it means that I get the variable by reference, which means that any changes in the $vvinside of the loop will affect the actual string, not the copy)

+1
source
// i only did the subarray part
$diskSizes = array("500", "300 GB", "200", "120 GB", "130GB");
$newArray = array();

foreach ($diskSizes as $diskSize) {
    $newArray[] = str_replace('GB', '', $diskSize);


}

// look at the new array
print_r($newArray);
+1
source

Source: https://habr.com/ru/post/1744863/


All Articles