2

I have an array in PHP, which may contain elements of various types. How can I keep only the elements that are strings, and remove all the others?

I know I can do

foreach ($array as $key => $val)
  if (gettype($val) !== 'string')
    unset($array[$key]);

But I would like an easier way to do it.
Note: I don't care about the array's keys and whether they stay the same or not.

1 Answer 1

4

You can do it in one line using PHP's functions array_filter() and is_string().

$new = array_filter($array, "is_string");

array_filter() keeps only the elemets of an array which, if passed to the callback function (is_string() in this case) will have the callback return true.

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

6 Comments

Why ask and answer instantly? :D You just wanted to share this?
@bali182 we explicitly encourage this when folks discover something, or solve a problem that took some time. It's just sharing something in the form of a question someone hoping to know it would ask. You're welcome to post a separate answer if you like.
No, the answer is absolutely correct, I just did not find the question that much extraordinary to randomly share it.
Might be worth mentioning that you can use several of the is_ functions as the callback to manage arrays (you might want to remove all non-int, or non-floats)
@bali182 It's a useful question for beginners, and the title is very descriptive (folks will find it). It's come up before but the way the questions were asked doesn't lend very well to finding them, so I'm happy to have this one around I suppose :)
|

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.