Ben Fortune
Ben Fortune

Reputation: 32118

String showing wrong length after going through function

I have the following function in my class.

public function checkPostcodeFormat($postcode) {
    if (strlen($postcode) === 7 && substr($postcode, 5) !== " ") {
        return substr($postcode, 0, 4) . ' ' . substr($postcode, 4, 3);
    } elseif (strlen($postcode) === 6 && substr($postcode, 4) !== " ") {
        return substr($postcode, 0, 3) . ' ' . substr($postcode, 3, 3);
    } else {
        return $postcode;
    }
}

If the postcode is returned via the substr functions it's fine, but if it's returned in the else section a var_dump() shows it to be the wrong length.

var_dump($_POST["postcode"]);

shows

string(7) "ab1 1ab"

Whereas

var_dump($class->checkPostcodeFormat($_POST["postcode"]));

shows

string(8) "ab1 1ab"

What could be causing the string to grow in length, if it's just being returned through the function?

Upvotes: 1

Views: 1203

Answers (3)

Amal Murali
Amal Murali

Reputation: 76666

If the $postcode is of the format ab1 1ab, then the first if condition will evaluate to TRUE and the code inside that if block will be executed. For the above input, substr($postcode, 5) will return the string ab. So, substr($postcode, 5) !== " ") will always be TRUE as long as the length of the post code is 7. And you're just adding an additional space when returning the string.

It's a good idea to remove all the space before working on your strings. I've improved the function as follows:

public function checkPostcodeFormat($postcode) {
    // remove all spaces in the post code
    $postcode = preg_replace('/\s+/', '', $postcode);

    if (strlen($postcode) === 6) {
        return substr($postcode, 0, 3).' '.substr($postcode, 3);
    } elseif (strlen($postcode) === 7) {
        return substr($postcode, 0, 4).' '.substr($postcode, 4);
    } 
}

Test cases:

var_dump( checkPostcodeFormat('AB11AB'));
var_dump( checkPostcodeFormat('AB121AB'));

Output:

string(7) "AB1 1AB"
string(8) "AB12 1AB"

Upvotes: 2

Bhavik Shah
Bhavik Shah

Reputation: 2291

Explanation:

your if condition is returning 8 characters string

substr($string, $start, $length)

So, when you input "ab1 1ab"

in if condition

1)substr($postcode, 0, 4) return "ab1 " <=== first space comes from here
2)then you appends space <=== another one from here

and then

3)substr($postcode, 4, 3) appends "1ab"

together they return "ab1 1ab" <=== two spaces between

Upvotes: 1

Vahe Shadunts
Vahe Shadunts

Reputation: 1966

Your code duplicates spaces, Your return is "ab1 1ba", but browser shows only one.

http://sandbox.onlinephpfunctions.com/code/49a75148d3d5236359776b33a4701789dccd25bf

Upvotes: 0

Related Questions