-1

I have an array as shown below, How to convert the above array1 into array2 form?

array1

Array
(
[0] => Array
    (
        [0] => 500 GB
    )

[1] => Array
    (
        [0] => 100 GB
    )

 )

array2

Array
    (
        [0] => 500 GB
        [1] => 100 GB
 )
Adrian Veidt
  • 280
  • 5
  • 17

1 Answers1

1
$yourArray = [[0 => '500 GB'], [0 => '100 GB'], [1 => '200 GB']];
$result = array_filter(
    array_map(
    function($element) {
        if (isset($element[0])) {
            return $element[0];
        }

        return;
    },
    $yourArray
    ),
    function($element) {
        return $element !== null;
    }
);

echo var_dump($result); // array(2) { [0]=> string(6) "500 GB" [1]=> string(6) "100 GB" }

This will work only with php >= 5.4 (because of array short syntax). If you're running on older versione, just substitute [] with array()

Explaination

array_filter is used to exclude certain values from an array (by using a callback function). In this case, NULL values that you get from array_map.
array_map is used to apply a function to "transform" your array. In particular it applies a function to each array element and returns that element after function application.

DonCallisto
  • 29,419
  • 9
  • 72
  • 100