php compare 01 to 1 from datetime object - php

DateTime object outputs 01, 02, 03 etc when I
use
$num = $dt->format('d');
to get the day number
Then I compare the $num value if it's
the first day of the month like so:
if ($num == 1)
but the $num value is '01'.
Now php compares it as expected
var_dump($num == 1)
returns true
I was thinking, should this be enough for me
or I should enclose the $num variable with an intval
like so:
intval($num)
this way if it is 01 it will display '1'

Basically $num = $dt->format('d') returns a String.
If you have == as a Comparison Operators and the two values are not from the same data type, PHP try to match them.
So in your case ($num == 1) you are comparing a String with a literal Integer
Therefore PHP is trying to converting the Sting into a Integer (only for the comparison).In the end you are already comparing two Integers.
The type conversion does not take place when the Comparison Operator is === or !== as this involves comparing the type as well as the value.So with $num = '1';, a comparison like $num === 1 would always return false.If you like to strip of leading zeros but don't convert the data type, I would use: $num_as_str = ltrim($num,'0');
If you like to convert the variable to an Integer use this:
$num_as_int = intval($num);
From the PHP manual:
String conversion to numbers
When a string is evaluated in a numeric context, the resulting value and type are determined as follows.
The string will be evaluated as a float if it contains any of the characters '.', 'e', or 'E'. Otherwise it will be evaluated as an integer.
The value is given by the initial portion of the string. If the string starts with valid numeric data, this will be the value used. Otherwise, the value will be 0 (zero). Valid numeric data is an optional sign, followed by one or more digits (optionally containing a decimal point), followed by an optional exponent. The exponent is an 'e' or 'E' followed by one or more digits.

Everything written by Webdesigner is right, but you can simply get the day number without leading zero by 'j' parameter:
$num = $dt->format('j');
So you can compare it with an ordinary numbers without any explicit type cast.

Related

string being treated as a number when using if statement

i am using an if statement to compare 2 variables against each other, mainly in this case barcodes. i have noticed if they are leading with zeros and the only difference is one variable as more zeros at the beginning and the rest is the same its giving a true result as if they are the same, which in INT/NUMBER format that would be true, however i have checked and both are strings, so cant get my head around why it thinks "000005" and "0000005" are the same when they are not.
echo "<pre>";
$params['barcode_new'] = "0000005";
$params['barcode_old'] = "000005";
echo "var type : " .gettype($params['barcode_new']) ."<br>";
if ($params['barcode_old'] == $params['barcode_new']) {
echo "Master barcode already set to {$params['barcode_new']} <br>";
print_r($params);
}
Strings will be compared per character. Numbers by their value. So the strings differ and numbers will be equal. For type correctness use === to check if the values are identical and == if they are equal (e.g. numbers)
<?php
var_dump("0000005" == "000005");
var_dump("0000005" === "000005");
?>
bool(true)
bool(false)
Use Identical === operator instead. With === it will not convert the values and will match for the exact. Try with -
if ($params['barcode_old'] === $params['barcode_new']) {
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.

PHP: Strange behaviour with variable assignment

I'm declaring a var $t and assigning it a value of 0. I then reassign $t a new value of test. It then appears that $t is both 0 AND test. Here's the code:
$t = 0;
$t = "test";
if($t == 0 && $t == "test"){
echo "unexpected";
}else{
echo "expected";
}
The output is:
"unexpected"
Can someone please explain what is going on here? Is $t really two different values (0 and test) at the same time or am I missing something?
This "strange" behaviour results in because of PHP's type juggling. Since you're using loose comparison == to compare to an integer 0 the string test is being converted to an integer, which results in conversion to 0. See the Loose comparison == table. There in the row with the string php you'll see that it equals to the integer 0, which applies to all strings.
You should be using strict (type) comparison operators, i.e. ===.
You're not appending or concatenating so it shouldn't be. Try the identical comparison operator instead.
if($t === 0 && $t === "test"){
....
}
PHP MANUAL STATES:
The value is given by the initial portion of the >string. If the string starts with valid numeric >data, this will be the value used. Otherwise, the >value will be 0 (zero). Valid numeric data is an >optional sign, followed by one or more digits >(optionally containing a decimal point), >followed by an optional exponent. The >exponent is an 'e' or 'E' followed by one or >more digits.
http://il.php.net/manual/en/language.types.string.php#language.types.string.conversion
So $t == 0 is true. You have to use strict comparison ===
Hey buddy use "===" operator for your comparison.
In php we can assign any value to a simple variable, it holds numeric, float, character, string, etc.
So always use "===" operator for unique or same value matching.

array_search can't find element which is clearly there

Why does the following code work:
$test = array(0=>'test1','field0'=>'test2',1=>'test3','field1'=>'test4');
echo array_search('test4',$test);
But the following doesn't:
$test = array(0=>0,'field0'=>'test2',1=>'test3','field1'=>'test4');
echo array_search('test4',$test);
If you had a mixed array from say mysql_fetch_array($result,MYSQL_BOTH) and took the keys which you needed to search you wouldn't be able too - it would never progress further than 0.
Try to do array_search('test4',$test, TRUE);. The 3rd parameter tells it to use === instead of == when comparing.
Since your array holds both strings and numbers, when it compares to the 0 (the 1st element), it converts 'test4' to a number (it stops at the 1st non-numeric character) and it happens to match.
What I mean is: 'test4' == 0 => 0 == 0 => true.
When you pass TRUE as the 3rd parameter, it uses ===, and 'test4' === 0 is automatically false since the types don't match, there is no conversion.
The solution = force the 0 value to be a string:
$test = array(0=>0,'field0'=>'test2',1=>'test3','field1'=>'test4');
foreach ($test as $k=>$v){ $test[$k] = (string) $v; }
echo array_search('test4',$test);
You can't search a number for a string and expect a good result.
My guess is it sees the value as a number, so it converts your string to a number (which it can't) so that string gets converted to a 0. So the value of 0 equals the search string, which also equals 0, and there's your result.
If the value is 1, it won't match as the search string gets converted to a 0 (as you can't convert a string to a number) so it wouldn't match in the following.
$test = array(0=>1,'field0'=>'test2',1=>'test3','field1'=>'test4');
You'll only get your exact case scenario when that value in the array is 0.

Why is 1 == '1,2' true? [duplicate]

This question already has answers here:
Comparing String to Integer gives strange results
(5 answers)
Closed 8 years ago.
Just curious how PHP type casting work for this case.
var_dump(1 == '1,2') // boolean(true)
That is because 1 is an integer here and when it is compared to a string 1,2 , this string will be casted to an integer , which returns 1.
How does casting a string 1,2 return 1 ?
echo int('1,2'); // prints 1
So when it is compared to your 1 , this will be obviously returning true on your var_dump
From the PHP Docs.. (Basic Comparison Test)
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.
Source
It's interpreted as:
var_dump(1 === (int) '1,2');
"1,2" casted to int will return 1, as anything after last parsed digit is being cutted off (,2 in this case).
Remember that comma (,) is not a decimal point separator, dot (.) is:
var_dump((float) '1,3', (float) '1.3');
Results in:
(float) 1
(float) 1.3
Casting can be often very unintuitive, that's why you should almost always use === operator, which doesn't create casts.
If you use ==, php will type cast the right side value to the left side value.
In this case '1,2' will be type cast to 1 and return true.
Even var_dump( 1== "1dfuiekjdfdsfdsfdsfdsfsdfasfsadf" ); will return true.

Compare string "numerically first"

I want to compare two string "numerically". I mean like 2C is less than 11A. I tried this and it's not working:
if("2A" < "11A"){
echo "First corect";
}
if(strcmp("2A", "11A") < 0){
echo "Last corect";
}
echo "Tests completed";
You are looking for strnatcmp (or its case-insensitive sibling, strnatcasecmp).
This will compare the numeric parts of your input as numbers (placing "2whatever" before "11whatever") and the textual parts as text (placing "2a" before "2b").
Try it like this:
if((int) '2A' < (int) '11A'){
echo "First correct";
}
You can also take a look at: http://php.net/manual/en/function.intval.php
if(intval(0x2A) < intval(0x11A)){
echo "First corect";
}
else
{
echo "Tests incompleted";
}
try this code
Write a function that:
Tokenizes each String into a List <Object> where each object can be a String or Integer with the Integers being created from a contiguous string of digits between non-digits, the Strings being contiguous non-digits between any 2 digits.
In a loop compare the two Lists element by element. If the type of the objects doesn't match (i.e. comparing an Integer to a String) make the less/greater decision on which you want to sort as smaller, letters or digits. If they match just do a less than, equals, greater than comparison.
If the two Nth elements in the list are equal, go on to compare the N+1th elements, otherwise return t/f based on the integer to integer or string to string comparison.

Categories