too long

I am creating a SMS app the following code is supposed to:

  1. check if the mobile/cell number is 11 characters long.
  2. check if the number starts with 07.

If neither of these conditions are met, it should remove the number from the array.

So the following numbers would be valid:

07123456789,07123456790,07123456791,07123456792,07123456793,07123456794

However the following wouldn't (and need to be removed):

0801458,07855488,6695522214124514

    $param["number"] = "07123456789,07123456790,07123456791,07123456792,07123456793,07123456794,0801458,07855488,6695522214124514";
    $number = explode(',', $param["number"]);
foreach($number as $num){
    if (!substr_compare($num, "07", 0, 3, false)) {
        unset($num);
    }
    elseif (substr_compare($num, "07", 0, 3, true)) {
        if(strlen($num) == 11) {
            $li .= "447" . substr($num, 2) . ',';
        }
    }
}
$il .= substr($li, 0, strlen($li)-1); 
echo $il;

//  $request = substr($request, 0, strlen($request)-1); 
//  return $n;
}

I also need to remove the final comma from the result.

Any help will be appreciated.

Thanks,

Kyle

You could build a new array of the valid numbers, and implode() that at the end.

$validNumbers = array();
foreach($number as $num){
    if (!substr_compare($num, "07", 0, 3, false)) {
        unset($num);
    }
    elseif (substr_compare($num, "07", 0, 3, true)) {
        if(strlen($num) == 11) {
            $validNumbers[] = "447" . substr($num, 2);
        }
    }
}
$il .= implode($validNumbers, ',');

regex should do:

preg_grep('/^07\d{9}$/', $number);

You could convert the numbers to an array, apply a filter to them and them glue them back together. Like this:

$numbers = "07123456789,07123456790,07123456791,07123456792,07123456793,07123456794,0801458,07855488,6695522214124514";
$array = explode(',', $numbers);
$filteredArray = array_filter($array, create_function('$item',
    'return strlen($item) == 11 && stripos($item, "07") === 0;'
));
echo implode(",", $filteredArray);

Or if you are using PHP 5.3, you could write the same thing as:

$numbers = "07123456789,07123456790,07123456791,07123456792,07123456793,07123456794,0801458,07855488,6695522214124514";
$array = explode(',', $numbers);
$filteredArray = array_filter($array, function($item) {
    return strlen($item) == 11 && stripos($item, "07") === 0;
});
echo implode(",", $filteredArray);

Which is a bit prettier. Both will output:

07123456789,07123456790,07123456791,07123456792,07123456793,07123456794

Further reading:

PHP.net array_filter()
PHP.net create_function()
PHP.net Anonymous functions