What's happening is that your array of area_codes that you read from the
file has newlines after each value.
array
0 => string '800
' (length=5)
1 => string '801
' (length=5)
2 => string '802
' (length=5)
3 => string '803
'
...and so on. When it's searching for "801" as a string, it doesn't
match "801\n". However, when you search for 801 as an int, it casts the
array value to an int as well, which drops the newline. Then it matches.
You could try just changing the one line to
$area_codes[] = trim(fgets($file_handle));
which works as you expect.
Jennifer
On 11/3/2009 9:26 AM, Jordan Schatz wrote:
> Anyone else have this experience? I generally don't have to typecast
> before a comparison, but in_array seems to require it?
>
> #! /usr/bin/php -q
> <?php
> //Test Data
> $primary_phone = '18017848218';
>
> // Load the zip code information
> $file_handle = fopen('./area_codes', 'r');
> $area_codes = array();
>
> while (!feof($file_handle)) {
> $area_codes[] = fgets($file_handle);
> }
>
> $area_code = substr($primary_phone, 1, 3);
> //Doesnt Work
> if (!in_array($area_code, $area_codes, FALSE)) {
> $error_message = 'PLEASE ENTER A VALID PHONE NUMBER!';
> $commit = 0;
> }
> //Works
> if (!in_array((int)$area_code, $area_codes, FALSE)) {
> $error_message = 'PLEASE ENTER A VALID PHONE NUMBER!';
> $commit = 0;
> }
>
> echo $error_message;
> ?>
>
> ----------
> Part of the area_codes file:
>
> 800
> 801
> 802
> 803
> 804
> 805
> 806
> 807
> 808
> 809
> 810
> 811
> 812
> 813
> 814
> 815
> 816
> 817
> 818
> 819
> 822
> 828
> 829
> 830
> 831
> 832
> 833
> 835
> 843
> 844
> 845
> 847
> 848
> 850
> 855
> 856
> 857
> 858
> 859
> 860
> 862
> 863
> 864
> 865
> 866
> 867
> 868
> 869
> 870
> 872
> 876
> 877
> 878
> 880
> 881
> 882
> 888
> 898
>
> _______________________________________________
>
> UPHPU mailing list
> [email protected]
> http://uphpu.org/mailman/listinfo/uphpu
> IRC: #uphpu on irc.freenode.net
_______________________________________________
UPHPU mailing list
[email protected]
http://uphpu.org/mailman/listinfo/uphpu
IRC: #uphpu on irc.freenode.net