0

I have the below line which takes a string, explodes it to an array by ',' and then trims any whitespace for each array item.

   $essentialArray = array_map('trim', explode(',', $essential_skills));

However when $essential_skills string = "" $essentialArray will equal Array ( [0] => )

But I need it to equal Array() so that I can call empty() on on it.

1
  • explode() is your problem, not array_map(), as it will never give you an empty array in response, which seems to be what you expect. Commented Jul 19, 2015 at 13:10

3 Answers 3

1

That is normal and logical behavior of the function.

Look at it this way: what does the explode() call return? An array with a single element which is the empty string. The array_map() call does not change that at all.

So you might ask: why does explode('') result in an array with a single element which is the empty string? Well, why not? It takes the empty string and splits it at all comma characters in there, so exactly no times. That means the empty string stays unaltered. But it does not magically vanish!

Sign up to request clarification or add additional context in comments.

Comments

1

The easiest solution here will be just filter result array, like this:

$essentialArray = array_filter(array_map('trim', explode(',', $essential_skills)));

but proper way is:

if ($essential_skills === '') {
$essentialArray = [];
}
else {
$essentialArray = array_map('trim', explode(',', $essential_skills));
}

Comments

0

explode return Array ( [0] => ), so you need to check your string before array_map

here is a one solution

   $exploderesult = $essential_skills ? explode(',', $essential_skills) : array();
   $essentialArray = array_map('trim', $exploderesult );

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.