André
André

Reputation: 25584

Removing non-integer entries from an array

I have a PHP array like this one:

array( [0] => 1
       [1] => 2
       [2] => 3
       [3] => Some strings
)

How can I remove an entry that is not an integer number from an array? I need to output this:

array( [0] => 1
       [1] => 2
       [2] => 3
)

Can someone give me a clue?

Upvotes: 25

Views: 17231

Answers (4)

Justin Levene
Justin Levene

Reputation: 1677

If you are sanitising for a database, try

$int_array = array_map('intval', $array);

Everything will be sanitised as an integer, however bad conversions will be 0

Upvotes: 0

Mohd Abdul Mujib
Mohd Abdul Mujib

Reputation: 13948

If you are consuming the input from $_POST or $_GET, then there is a problem with each of the following.

  • array_filter($array, 'is_numeric') will also accept fractional values eg. 2.5
  • array_filter($array, 'is_int'); will reject most int inputs as the values posted over $_GET or $_POST are considered as strings even if they contain valid integers.
  • array_filter($array, 'ctype_digit'); will reject inputs if they contain valid integers as it only matches integers that are represented as a string.

So the safest approach to filter an array for only valid Integers, is

array_filter($ids, function($e){ return ctype_digit( (string) $e );})

Upvotes: 3

Alfabravo
Alfabravo

Reputation: 7589

Have a look at Array_splice and is_int

Upvotes: 0

adlawson
adlawson

Reputation: 6431

Use array_filter with is_int

$filtered = array_filter($array, 'is_int');

Edit:

As noted in the comments, it may be a better solution to use one of the following instead.

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

Upvotes: 73

Related Questions