0

I have an array but the structure isnt good so I wanted it to change.

The array is an array with arrays in it, but 1 is always empty so I dont need this one, and therefor there's no need for a multilevel array.

Current array

array(

    [0] => array( 
        [0] => some value
        [1] => some value
    ),
    [1] => array( empty so this one must be removed )

)

The way that I want it to be

array( 
        [0] => some value
        [1] => some value
    )
1

4 Answers 4

2

You can use like below.

array_reduce($array, 'array_merge', array());

For Example:

$a = array(array(1, 2, 3), array(4, 5, 6));
$result = array_reduce($a, 'array_merge', array());

Result:

array[1, 2, 3, 4, 5, 6];
Sign up to request clarification or add additional context in comments.

Comments

1

You can use array_merge inside a loop. Something like -

$array = [
[1, 2],
[],
[4]
];
$temp = [];
foreach($array as $a) {
  $temp = array_merge($temp, $a);
}
print_r($temp);

Output

Array
(
    [0] => 1
    [1] => 2
    [2] => 4
)

Comments

0

This is a fairly cheap code wise way of flattening

$array = [[1, 2], []];
$flat = array_merge(...$array);

The problem is if the first level of the array isn't all arrays, it falls over

1 Comment

If worried about an element not being an array, you could adapt Sougata's answer and cast array_merge's second argument to an array.
0

Just loop over the array and add the non empty arrays elments, as explained below, (without using inbuilt function)

<?php
$array = [[1, 2], [], [4]];
$temp = [];
foreach($array as $a) {
   if(!empty($a)) {
      foreach($a as $b)
      $temp[] = $b;
   }
}

echo "<pre>";
print_r($temp);
/* result
Array
(
    [0] => 1
    [1] => 2
    [2] => 4
)
*/
?>

2 Comments

You can dump the empty check: $in = [[1, 2], [], [4]]; foreach($in as $a) foreach($a as $b) $out[] = $b;
@Progrock yes you are right, but in case if the array contains null or blank string it will append the element in the output e.g. [""] or [null]

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.