What will the following print? - php

What will the following code print?
print ‘’four’’ * 200;

It prints "0"
alt text http://mywebprogrammer.com/images/soAnswer.PNG
The result is to the left of the second line.
To see why this is you can do a quick test echo (int)'four'; this will attempt to explicitly cast the string 'four' to an integer which since it is not an integer will technicaly fail, resulting in a 0 which of course is equal to FALSE. If you replace the 'four' with '4', still a string, you can properly cast it to an integer and it will produce the result of 800 in the case of your example ("print '4' * 200").

Yes it would print zero "0" indeed. The thing is PHP will type cast the string value to an integer. This would result in 0 (Zero); and if you times any value with zero you'll get zero.
Good Question Roland!

Since the string cannot be casted to a number, the multiplication with a string will result in 0.

Related

Addition to number formed using number_format() php function

When i try to add a integer to 3 digit number formed using php number_format() function give right result but when number become 4 digit it give wrong output.
I have tried this. please explain me the reason behind this??
$num1=number_format(1000.5,2);
$num1+=1;
echo $num1;
Output:2
But
$num1=number_format(100.5,2);
$num1+=1;
echo $num1."\n";`
Output:101.5
number_format() returns a string not a number. It is there to format a numeric type (integer, float) to a string with a specific, desired "layout". So what you do is add the number 1 to the string resulting from number_format, which will try to cast the string back to a number, apparently resulting in 1 for the string cast as well, which gives you 2 total.
tl;dr; Do calculations on numbers only and then do number_format at the very end to output in a defined format.
$num1 = number_format(1000.5, 2);
var_dump($num1);
// => string(8) "1,000.50"
$num1 += 1;
var_dump($num1);
// => int(2)
Function number_format() returns string.
And that string is type cast to integer when you are adding 1
See Type Juggling
The quickest solution would be using str_replace() on your formatted number.
Something like this would do:
(float)str_replace( ',', '', $formatted_number )
By removing the commas from the string and asking for the float value, you'll get a usable number.

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.

Php, in_array, 0 value

I was trying to understand the in_array behavior at the next scenario:
$arr = array(2 => 'Bye', 52, 77, 3 => 'Hey');
var_dump(in_array(0, $arr));
The returned value of the in_array() is boolean true. As you can see there is no value equal to 0, so if can some one please help me understand why does the function return true?
This is a known issue, per the comments in the documentation. Consider the following examples:
in_array(0, array(42)); // FALSE
in_array(0, array('42')); // FALSE
in_array(0, array('Foo')); // TRUE
To avoid this, provide the third paramter, true, placing the comparison in strict mode which will not only compare values, but types as well:
var_dump(in_array(0, $arr, true));
Other work-arounds exist that don't necessitate every check being placed in strict-mode:
in_array($value, $my_array, empty($value) && $value !== '0');
But Why?
The reason behind all of this is likely string-to-number conversions. If we attempt to get a number from "Bye", we are given 0, which is the value we're asking to look-up.
echo intval("Bye"); // 0
To confirm this, we can use array_search to find the key that is associated with the matching value:
$arr = array(2 => 'Bye', 52, 77, 3 => 'Hey');
echo array_search(0, $arr);
In this, the returned key is 2, meaning 0 is being found in the conversion of Bye to an integer.
Try adding a third parameter true (strict mode) to your in_array call.
This is a result of the loose comparison and type juggling.
Loose comparison means that PHP is using == not === when comparing elements. == does not compare that the two variable types are equal, only their value, while === will ensure that they match in type and value (e.g. compare 0 == FALSE and 0 === FALSE).
So, basically, your in_array function is checking:
0 == 'Bye'
0 == 'Hey'
0 == 77
Note that the 52 will get lost due to the way you created your array.
So, note that if you do:
print (0 == 'Bye');
You will get 1. Apparently, PHP is type juggling the 'Bye' to 0, which is the same thing that will happen when you cast a string to an int, e.g. (int) 'string' will equal 0. Specific reference from the String conversion to numbers doc (Emphasis added):
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.
Apparently, the integer type takes precedence over the string type (i.e. it could just as easily be doing the comparison by casting the int 0 to a string, which would then return False). This is specified in the comparison operators doc:
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.
Thanks for an interesting question that led me to do some research and learn something new!
in_array is supposed to be used on indexed arrays ([0], [1], [2] etc), not with a dictionary as you have defined (key-value store).
If you want to check if your array $arr includes '0', try using the PHP function array_key_exists instead - http://php.net/manual/en/function.array-key-exists.php.
var_dump(array_key_exists(0, $arr));
Type compare (third parameter) needs more system resources and more time.
Simply do that:
$x=0;
$result=in_array($x.'',array('ABC','BAC','12c','54'));
var_dump($result);

PHP intval() behaviour?

This sounds to strange to me:
$test_1 = 'string';
$test_2 = '0';
var_dump(intval($test_1)); // Output: int 0
var_dump(intval($test_2)); // Output: int 0
$can_cast = intval($test_2) ? 'sure' : 'nope'; // Wrong!!!
So with a string to int conversion intval returns 0. Fine, but it returns 0 also when the string actually can be casted to zero (because is zero) thus valid.
How can one can distinguish between both (allows '0' as string and deny 'string')?
EDIT: ok let me say i know i can use is_numeric. But is_numeric('2.3') returns true, so it can't help. And:
$test = '0';
var_dump(is_numeric($test) && intval($test)); // Fail!!!
You could do a ctype_digit check before you cast (if you want only positive numbers). Alternatively you could do an integer validation using filter_var and FILTER_VALIDATE_INT. The integer validation will also check integer semantics, i.e. it will ensure that the integer is within the allowed range. You can also customize it for your needs through several options.

Categories