Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP filter array

I have a PHP array of strings. The strings are supposed to represent PIN codes which are of 6 digits like:

560095

Having a space after the first 3 digits is also considered valid e.g. 560 095.

Not all array elements are valid. I want to filter out all invalid PIN codes.

like image 583
user540472 Avatar asked Dec 13 '10 12:12

user540472


People also ask

What is array filter PHP?

Definition and Usage. The array_filter() function filters the values of an array using a callback function. This function passes each value of the input array to the callback function. If the callback function returns true, the current value from input is returned into the result array. Array keys are preserved.

What does array [] mean in PHP?

An array in PHP is actually an ordered map. A map is a type that associates values to keys.

Is value in array PHP?

The in_array() function is an inbuilt function in PHP that is used to check whether a given value exists in an array or not. It returns TRUE if the given value is found in the given array, and FALSE otherwise.

Is array check in PHP?

The is_array() function checks whether a variable is an array or not. This function returns true (1) if the variable is an array, otherwise it returns false/nothing.


2 Answers

Yes you can make use of regex for this.

PHP has a function called preg_grep to which you pass your regular expression and it returns a new array with entries from the input array that match the pattern.

$new_array = preg_grep('/^\d{3} ?\d{3}$/',$array);

Explanation of the regex:

^     - Start anchor
\d{3} - 3 digits. Same as [0-9][0-9][0-9]
 ?    - optional space (there is a space before ?)
        If you want to allow any number of any whitespace between the groups
        you can use \s* instead
\d{3} - 3 digits
$     - End anchor
like image 52
codaddict Avatar answered Sep 21 '22 04:09

codaddict


Yes, you can use a regular expression to make sure there are 6 digits with or without a space.

A neat tool for playing with regular expressions is RegExr... here's what RegEx I came up with:

^[0-9]{3}\s?[0-9]{3}$

It matches the beginning of the string ^, then any three numbers [0-9]{3} followed by an optional space \s? followed by another three numbers [0-9]{3}, followed by the end of the string $.

Passing the array into the PHP function preg_grep along with the Regex will return a new array with only matching indeces.

like image 26
Greg Avatar answered Sep 23 '22 04:09

Greg