4

I have a php array with strings and I'd like to delete the keys that have a string containing only numbers.

How can I do that?

3 Answers 3

13

Filtering the array would be the most elegant way:

$array = array_filter($array, 'is_numeric');

This returns an array with only those values for whom is_numeric() is true.

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

2 Comments

Yes indeed, it looks way more elegant than the answers below, but I'm searching for numeric-only strings.
If you need only digits, without any other symbols that may appear in a numeric string, you can filter with is_int.
4
foreach ($array as $key => $val)
    if (is_numeric($key)) // only numbers, a point and an `e` like in 1.1e10
        unset($array[$key]);

This unsets all the entries where there are only numbers.

8 Comments

That's basically CooPer answer with typo corrected. Give him some time to fix it instead of duplicating the answer - it was his idea.
Isn't he looking for numeric keys, not values?
@JanTuroň see the time... My answer is older than his?
@JanTuroň we post at same time
@bwoebi: eh, his answer appeared sooner in my browser. However, it were just couple of seconds, therefore I take back the -1 from me. Sorry.
|
4

Use this code

foreach($array as $key=>$value)
  if(is_numeric($value))
      unset($array($key));

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.