0

Is possible to remove all empty elements from a array except the first element? Looking at this example:

Original

Array (
[0] => val1
[1] => val2
[2] => val3
[3] => 
[4] => val4
[5] => val5
[6] => val6
[7] => 
[8] => val7
[9] => val8
[10] => val9
)

Desired Result

Array (
[0] => val1
[1] => val2
[2] => val3
[3] => 
[4] => val4
[5] => val5
[6] => val6
[7] => val7
[8] => val8
[9] => val9
)

Is this possible? Which is the best way to achieve this?

Thanks in advance for your help.

3
  • Create a foreach loop. Commented Jan 2, 2017 at 16:32
  • 1
    Of course you have tried a few things right? So show us a few! Commented Jan 2, 2017 at 16:34
  • Hi @RiggsFolly i am not expert on PHP, i tried the basic, array_filter but of course it remove all the empty elements, do you have any solution? Thank you. Commented Jan 4, 2017 at 15:56

2 Answers 2

1

Simple solution is:

$a = array(
    '0' => 'val1',
    '1' => 'val2',
    '2' => 'val3',
    '3' => '',
    '4' => 'val4',
    '5' => 'val5',
    '6' => 'val6',
    '7' => '',
    '8' => 'val7',
    '9' => 'val8',
    '10' => 'val9',
);
// special flag to check if empty 
// element already exists in new array
$has_empty = false;
$new_a = [];
foreach ($a as $el) {
    if (!empty($el) || !$has_empty) {
        $new_a[] = $el;
        if (empty($el)) {
            $has_empty = true;
        }
    }
}
echo'<pre>',print_r($new_a),'</pre>';
Sign up to request clarification or add additional context in comments.

Comments

1

You can use array_filter:

$first = false;
$result = array_filter($arr, function($k) use($first){
    if(empty($k) && !first){
       $first = true;
       return true;
    }
    return !empty($k);
})

Comments

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.