Want to protect your cyber security and still get fast solutions? Ask a secure question today.Go Premium

x
  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 406
  • Last Modified:

PHP trim() function compare not recognizing leading zeros

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
FourMat
Asked:
FourMat
  • 7
  • 4
  • 3
  • +1
1 Solution
 
Hugh McCurdyCommented:
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
 
Hugh McCurdyCommented:
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
 
Hugh McCurdyCommented:
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
Concerto Cloud for Software Providers & ISVs

Can Concerto Cloud Services help you focus on evolving your application offerings, while delivering the best cloud experience to your customers? From DevOps to revenue models and customer support, the answer is yes!

Learn how Concerto can help you.

 
FourMatAuthor Commented:
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
 
nemws1Database AdministratorCommented:
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
 
nemws1Database AdministratorCommented:
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
 
Hugh McCurdyCommented:
!== 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
 
Hugh McCurdyCommented:
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
 
Ray PaseurCommented:
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
 
Ray PaseurCommented:
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
 
Ray PaseurCommented:
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
 
FourMatAuthor Commented:
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
 
Hugh McCurdyCommented:
Oops, my bad.  You were trying to see if they were different.  Thanks for the points.
0
 
Ray PaseurCommented:
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
 
FourMatAuthor Commented:
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
 
Hugh McCurdyCommented:
Thanks Ray.  I like starting off the day with a chuckle.

Hugh
0

Featured Post

Receive 1:1 tech help

Solve your biggest tech problems alongside global tech experts with 1:1 help.

  • 7
  • 4
  • 3
  • +1
Tackle projects and never again get stuck behind a technical roadblock.
Join Now