Solved

PHP trim() function compare not recognizing leading zeros

Posted on 2011-09-26
16
314 Views
Last Modified: 2012-08-13
I have a script that I am using to compare values input values, to see if they are different.  If they are then I want to perform the replace functions.

I am having an issue with numbers that have a preceding 0 on them, such as a 12 digit UPC code.  Here is my code snippet:

if (trim($HTTP_POST_VARS['product_new_upc'][$id]) != trim($HTTP_POST_VARS['product_old_upc'][$id]))

Open in new window


If the old number was 79340242319 and the new number needs to be 079340242319 the code is not recognizing that there is a difference and not initiating the update to the database field.  I have tried other combinations of number and character changes, but it only seems to happen with the preceding zero

The manual on the PHP website for trim() doesn't say anything about trimming out the preceding 0 by default.  

Is there anything in this function that might be causing this?  If so, is there a way around it?
0
Comment
Question by:FourMat
  • 7
  • 4
  • 3
  • +1
16 Comments
 
LVL 13

Expert Comment

by:Hugh McCurdy
ID: 36601861
My first reaction is that PHP is noticing two numeric strings and noticing they have the same numeric value.

Have you tried a string compare?    strcmp()
0
 
LVL 13

Expert Comment

by:Hugh McCurdy
ID: 36601889
Yes, page 42 of "Programming PHP" published by O'Reilly, states that the = comparison in this case will be a numeric comparison.

What you want is a string comparison as these "numbers" are really numbers.  A phone number isn't really a number either.  We don't normally add 7 to a phone number and expect a meaningful result.

For information on strcmp(), I suggest you look here -- http://www.w3schools.com/php/func_string_strcmp.asp
I'm pretty sure strcmp will do what you want done.  Please let me know either way.  (However, I'll be out for a few hours this evening).
0
 
LVL 13

Accepted Solution

by:
Hugh McCurdy earned 500 total points
ID: 36601923
I haven't tested this but it might work

      

if (strcmp(trim($HTTP_POST_VARS['product_new_upc'][$id]), trim($HTTP_POST_VARS['product_old_upc'][$id])) == 0 )

Open in new window

0
 

Author Comment

by:FourMat
ID: 36601965
Thanks for the point in the right direction, I took a look at the properties of the != operator at php.net and found this:

If you compare a number with a string or the comparison involves numerical strings, then each string is converted to a number and the comparison performed numerically. These rules also apply to the switch statement. The type conversion does not take place when the comparison is === or !== as this involves comparing the type as well as the value.

I replace the != with !== and it seemed to work.  Do you see any pitfalls in this method?
0
 
LVL 23

Expert Comment

by:nemws1
ID: 36601995
Just to clarify (in case anybody doesn't want to go and read the manual page for strcmp(), which I highly recommend they do), strcmp returns a non-zero value if the two strings are not equal, thus a simple if(strcmp("01","1")) will result in a true value (in this case, the result is -1, but that is still non-zero, so if() will return true)
0
 
LVL 23

Expert Comment

by:nemws1
ID: 36602010
For code maintainability purposes, I would still go with hmccurdy's answer and strcmp().  It is clearer what's going on rather than using !==.
0
 
LVL 13

Expert Comment

by:Hugh McCurdy
ID: 36602062
!== will work as well.  I didn't suggest that because of maintenance purposes.  It might be hard to quickly see, at first glance, the difference between != and !==.  strcmp stands right out and also makes it clear that you really mean to be comparing strings and not numbers.  One of the most important things in writing software is to not confuse the maintenance programmer down the road.

Alternatively, if you want to use !==, I strongly recommend that you add a comment on the line above to make it clear that you mean to perform a string comparison because part numbers aren't really numbers.  They are (in your case) numeric strings.
0
 
LVL 13

Expert Comment

by:Hugh McCurdy
ID: 36602077
In closing, before I leave for my appointment, I agree that you should read the strcmp() documentation.  I suggest you read all the str*() function documentation for PHP.  If you even find yourself working in C, you'll have a head start.  Plus, it's good to know about all the tools you have in a programming language.  (Even goto - ugh)
0
6 Surprising Benefits of Threat Intelligence

All sorts of threat intelligence is available on the web. Intelligence you can learn from, and use to anticipate and prepare for future attacks.

 
LVL 108

Expert Comment

by:Ray Paseur
ID: 36602462
You have encountered the "loose typing" of PHP.  Use == to test for loosely typed equality.  Example: 03 == 3.  Use === to test for strictly typed identicality.  Example: 3 === 3, however '3' !== 3 because one is string and one is integer.  The man page explains it here.
http://us3.php.net/manual/en/types.comparisons.php
0
 
LVL 108

Expert Comment

by:Ray Paseur
ID: 36602472
In addition to understanding the type comparisons, you might also want to learn about ltrim() and rtrim().  Note the second argument for these functions.
http://us3.php.net/manual/en/function.ltrim.php
http://us3.php.net/manual/en/function.rtrim.php

And before you get too far into the development using $HTTP_POST_VARS, please note that it is deprecated.  You probably want $_POST instead.
http://us3.php.net/manual/en/reserved.variables.post.php

There are some other things that you may find lying around in old code that also need to be refactored:
http://us3.php.net/manual/en/migration53.deprecated.php

Best of luck with it, ~Ray
0
 
LVL 108

Expert Comment

by:Ray Paseur
ID: 36602529
One last, then I'll sign off.  In older version of PHP the array keys were loosely typed.  In my current version 5.3.8 they are no longer loosely typed, sort of.  You can run this script to see how your version of PHP handles leading zeros and/or character strings in array keys.

Best to all, over and out, ~Ray
<?php // RAY_temp_fourmat.php
error_reporting(E_ALL);
echo "<pre>";

$arr[] = "Zero";
$arr[] = 'One';
$arr[] = 'Two';
$arr[] = 'Three';

print_r($arr);

// TRY TO ASSIGN A KEY=>VALUE USING A QUOTED NUMERIC ARRAY KEY
$key = '03';
if ($key == 3) echo PHP_EOL . "$key == 3" . PHP_EOL;

$arr[$key] = 'SURPRISE';
$arr['1']  = 'SURPRISE';
$arr['01']  = 'SURPRISE';
print_r($arr);

foreach ($arr as $key => $value)
{
    $type = gettype($key);
    echo PHP_EOL . "$key OF TYPE $type => $value";
}

Open in new window

0
 

Author Comment

by:FourMat
ID: 36639188
hmccurdy:  Sorry for the delay in response, had to take a few hours myself.

The !== syntax works, but I am trying to follow your recommendations and use the strcmp for the recommended ease of maintenance, and for some reason, wasn't working.

I read through the docs to learn what it was doing and realized that it needed to be not equal to, so I changed the == 0 to a != 0 and it's working fine now.


Ray: currently I am using 5.2.14, (updating tomorrow to 5.2.17).  The script that I am working on is an older one that was written a while back and I'm just doing some bug fixing.  Improvement suggestion noted and thanks!

These are the results returned when I ran your script:
Array
(
    [0] => Zero
    [1] => One
    [2] => Two
    [3] => Three
)

03 == 3
Array
(
    [0] => Zero
    [1] => SURPRISE
    [2] => Two
    [3] => Three
    [03] => SURPRISE
    [01] => SURPRISE
)

0 OF TYPE integer => Zero
1 OF TYPE integer => SURPRISE
2 OF TYPE integer => Two
3 OF TYPE integer => Three
03 OF TYPE string => SURPRISE
01 OF TYPE string => SURPRISE
0
 
LVL 13

Expert Comment

by:Hugh McCurdy
ID: 36658802
Oops, my bad.  You were trying to see if they were different.  Thanks for the points.
0
 
LVL 108

Expert Comment

by:Ray Paseur
ID: 36708806
Before you do your update to 5.2.17, you might want to read this line from the home page of php.net:

All PHP users should note that the PHP 5.2 series is NOT supported anymore. All users are strongly encouraged to upgrade to PHP 5.3.8.
http://www.php.net/

@hmccurdy: regarding "goto"
http://xkcd.com/292/
0
 

Author Comment

by:FourMat
ID: 36708970
Ray,

Yeah, I know I'm behind.  I have a set of scripts with the ereg() deprecated and I'm worried about breaking sites.  I know that I can use preg_replace() but I just haven't had time to comb through all of the code to make it happen. If I do the upgrade from 5.2.14, to 5.3.8 will I have a bunch of warnings thrown up at my users? Or would it be safe to do the upgrade and attend to the function changes as I get to them?

0
 
LVL 13

Expert Comment

by:Hugh McCurdy
ID: 36709527
Thanks Ray.  I like starting off the day with a chuckle.

Hugh
0

Featured Post

IT, Stop Being Called Into Every Meeting

Highfive is so simple that setting up every meeting room takes just minutes and every employee will be able to start or join a call from any room with ease. Never be called into a meeting just to get it started again. This is how video conferencing should work!

Join & Write a Comment

Any business that wants to seriously grow needs to keep the needs and desires of an international audience of their websites in mind. Making a website friendly to international users isn’t prohibitively expensive and can provide an incredible return…
Boost your ability to deliver ambitious and competitive web apps by choosing the right JavaScript framework to best suit your project’s needs.
The viewer will learn how to create and use a small PHP class to apply a watermark to an image. This video shows the viewer the setup for the PHP watermark as well as important coding language. Continue to Part 2 to learn the core code used in creat…
The viewer will learn how to create a basic form using some HTML5 and PHP for later processing. Set up your basic HTML file. Open your form tag and set the method and action attributes.: (CODE) Set up your first few inputs one for the name and …

757 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

20 Experts available now in Live!

Get 1:1 Help Now