1

Thanks in advance, I feel like I'm overlooking something very simple. I have some numerical zip codes that I need to run through a function...however, I need to validate that the input is a five digit string. But, no matter how I try to cast the number to string, it's failing. Is there some other way I should be encoding or formatting?:

<?php
$code=07307;
$wrapped_code='07307';
$castcode=(string)$code;
$strcode=''.$code;

echo (preg_match('/^\d{5}$/', $code))?'success with code<br/>':'code failed, saw:'.$code."<br/>";
echo (preg_match('/^\d{5}$/', $wrapped_code))?'success with wrapped_code<br/>':'wrapped_code failed, saw:'.$wrapped_code."<br/>";
echo (preg_match('/^\d{5}$/', $castcode))?'success with castcode<br/>':'castcode failed, saw:'.$castcode."<br/>";
echo (preg_match('/^\d{5}$/', $strcode))?'success with strcode<br/>':'strcode failed, saw:'.$strcode."<br/>";
?>

2 Answers 2

3

Try this code:

echo 07307;

You will find, counter-intuitively, that you get the result 3783. This is because numbers starting in 0 are treated as octals, that is, in base 8. So when you cast 07307 to a string, you get "3783". If leading zeros are important, you should be using a string in the first place.

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks. I knew I needed to work with it as a string, and it turned out I had a complicating error: I was importing the initial values from a CSV file, and when the column of interest was the LAST, I wasn't properly removing newlines...I don't know why that mattered for this aspect of it, but when I added a dummy column after it, things behaved as they should.
1

From what you said you want to achieve, I think you'd be better off using is_numeric and strlen, as is_numeric checks whether a variable is a number or a numeric string.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.