Sami
Sami

Reputation: 477

Issues with integer operations

function sendSms($toPhone,$message){
    $toPhone=intval(trim($toPhone));
    if(strlen($toPhone)== 8 && $toPhone{0}==9){

                    //sending sms

    }else{
        return "error";
    }

}

I am trying to validate mobile numbers for sending SMS. The first line trims the phone number string and then converts it to an integer. In the if statement, I want to make sure that the number length is 8 digits and it begins with 9. This function always goes for the else even if the number is correct( 8 digits and begins with 9). What could be the issue here.

Upvotes: 0

Views: 57

Answers (4)

David Müller
David Müller

Reputation: 5351

After you converted the phone number to an integer with $toPhone=intval(trim($toPhone));,, you can't access the digits in the way you are trying with $toPhone{0}, because you operate on a number and not on a string any more.

See this isolated example:

$number = 987654321;
var_dump($number{0}); //NULL

However, substr would be capable of doing this:

$number = 987654321;
var_dump(substr($number, 0, 1)); //string(1) "9"

Converting a whole number to integer isn't a good idea anyways, because users might enter the number with spaces in between or signs like + and /. Better search for an already existing approach to validate phone numbers.

Take a look here, where the topic "validate mobile phone numbers" is covered in more detail: A comprehensive regex for phone number validation

Upvotes: 1

TheHorse
TheHorse

Reputation: 2797

You can remove from $toPhone all not digits

function sendSms($toPhone,$message){
    $_phone = '';
    for ($i = 0; $i < strlen($toPhone); $i++)
    {
        if (is_numeric($toPhone[$i]))
           $_phone .= $toPhone[$i];
    }

    if(strlen($_phone)== 8 && $_phone[0]=='9'){
           //sending sms
    }else{
       return "error";
    }    
}

Upvotes: 1

Sergejs Rižovs
Sergejs Rižovs

Reputation: 458

You convert variable to integer and apparently $toPhone[0] works on strings only.

The same function without intval() works as you wanted.

function sendSms($toPhone, $message)
{
    $toPhone = trim($toPhone);
    if(strlen($toPhone) == 8 && $toPhone[0] == 9){
        //sending sms
    } else {
        return "error";
    }
}

Upvotes: 0

Petah
Petah

Reputation: 46060

Why not regex?

$valid = preg_match('/^9[0-9]{7}$/', trim($phone));

Upvotes: 1

Related Questions