php compare 01 to 1 from datetime object
Get the solution ↓↓↓Solution:
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);
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.
Answer
Solution:
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.
Share solution ↓
Additional Information:
Link To Answer People are also looking for solutions of the problem: call to undefined function mysqli_connect()
Didn't find the answer?
Our community is visited by hundreds of web development professionals every day. Ask your question and get a quick answer for free.
Similar questions
Find the answer in similar questions on our website.
Write quick answer
Do you know the answer to this question? Write a quick response to it. With your help, we will make our community stronger.