views:

50

answers:

4

Each item in my array is an array of about 5 values.. Some of them are numerical ending in "GB".. I need the same array but with "GB" stripped out so that just the number remains.

So I need to iterate through my whole array, on each subarray take each value and strip the string "GB" from it and create a new array from the output.

Can anyone recommend and efficient method of doing this?

+1  A: 

You can create your own custom function to iterate through an array's value's, check if the substring GB exists, and if so, remove it. With that function you can pass the original array and the function into array_map

Anthony Forloney
+1  A: 
$arr = ...

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

This actually keeps the original arrays intact with the new strings. (notice &$vv, which means that i'm getting the variable by reference, which means that any changes to $vv within the loop will affect the actual string, not by copying)

Jacob Relkin
+1  A: 
// 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);
Axsuul
+2  A: 

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

It's a lot less awkward than traversing an array with its values by reference (correctly).

cletus