Tuesday, 29 January 2013

PHP-Removing Strings or non-integer values from an array?

I you want to remove some non-integer values from an array or string values fro an array, follow the following steps:
$array1= array( [0] => 1
         [1] => 2
         [2] => 3
         [3] => Some strings
        );
 
The above contains the array with some strings in it in the 4th index.
We remove it by 
 
$filtered_array = array_filter($array1, 'is_numeric');

Yes. We must use array_filter() in PHP to filter non-integer array values.

We can also use the below code to achieve same result.
$filtered_array = array_filter($array1, 'ctype_digit');
$filtered_array = array_filter($array1, 'is_int');

Now it'll print all array values expect the index which has 'Some strings'.

No comments:

Post a Comment