2

I currently have an variable that contains the below array. Each part of the array is user submitted how would I go about checking whether each part of the array is an integer value and if it's not then dropping that part of the array?

Array ( [0] => 3 [1] => 4 [2] => 17 [3] => 5 [4] => 6 [5] => 11 [6] => 7 [7] => 8 [8] => 9 [9] => 15 [10] => 16 [11] => 18 [12] => 10 [13] => 12 [14] => 13 [15] => 14 )

I'm storing the array inside $forums and I've tried array_map("ctype_digit", $forums);

4
  • $forums is where I'm storing the array and I've tried array_map("ctype_digit", $forums); Commented Apr 7, 2016 at 14:09
  • 3
    use array_filter Commented Apr 7, 2016 at 14:10
  • is_numeric($num) with array_filter Commented Apr 7, 2016 at 14:12
  • Your question title says "numeric", the description says "integer" and ctype_digit() returns true only for strings consisting entirely of digits ... Terminology is important, you need to be precise in explaining what you want first. Commented Apr 7, 2016 at 14:14

4 Answers 4

6

You can use array_filter to get the result array with 'is_numeric' parameter:

$yourArray = Array( [0] => 3 [1] => 4 [2] => 17 [3] => 5 [4] => 6 [5] => 11 [6] => 7 [7] => 8 [8] => 9 [9] => 15 [10] => 16 [11] => 18 [12] => 10 [13] => 12 [14] => 13 [15] => 14 );
$filtered = array_filter($yourArray, 'is_numeric');
Sign up to request clarification or add additional context in comments.

Comments

2

Use array_filter with is_int

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

You can use like this. Simple.

Comments

1

Simply

<?php

$a = [1,2,3,4,5,6,'test',7,8,9];

foreach($a as $key => $value) {
    if(!is_int($value)) {
        unset($a[$key]);
    }
}

Comments

0

Loop through the array and check value array is numeric or not if not then delete that key.

foreach($yourArray as $key => $value)
{
   if (!is_numeric($value))
   {
      unset($yourArray[$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.