PHP strcmp result int meaning - php

In php, there is a built-in function strcmp to compare if two strings are same or not.
Returning value is integer number that if the first parameter is greater than the second I get > 0, if not < 0 and if the same 0.
So the part I don't get is comparing string as number.
Does PHP convert string to number and if so how's PHP converting?
$a = 'acorn';
$b = 'zebra';
var_dump( strcmp($a, $b) ); // -25 <- what's this number? seems like alphabetical position...nnn
Doesn't it really matter what number I get, shall I just take what it is?

Looking at the PHP: strcmp doc :
Returns < 0 if str1 is less than str2; > 0 if str1 is greater than
str2, and 0 if they are equal.
So yes, you can use it as it is to compare your string.
But if you want to understand the number returned by the function, it depend on the characters that makes the strings.
In ASCII :
A=65 < B=66 < C=67 ....
So if the string are different, one is gonna be greater than the other.
So you can also test it easily with a short script :
<?php
$a='A';
$b='B';
$c='C';
//Return -1 because $a is smaller than $b by one (65 < 66 )
echo strcmp($a,$b);
//Return -2 because $a is smaller than $c by two (65 < 67 )
echo strcmp($a,$c);
//Return -1 because $b is smaller than $c by one (66 < 67 )
echo strcmp($b,$c);
//Return 1 because $c is greater than $b by one (67 > 66 )
echo strcmp($c,$b);
//Return 2 because $c is greater than $a by two (67 > 65 )
echo strcmp($c,$a);

strcmp is using for comparing two strings in PHP.
If your result is greater the 0 its mean variable one ($a) is greater then Var2($b)
if return result is less then 0 its mean $b is greater and If result is equal to 0 its mean both strings are equal to each other.
$a="Hello world!";
$b= "Hello world!";
var_dump(strcmp($a, $b)); // result is 0
$a = "Hello";
$b = "Hello World";
var_dump(strcmp($a, $b)); // Outputs: -6
and If you want to see difference then you can use this
$a = 'some-content-here-example';
$b = 'some-content-example';
$asp = preg_split('//', $a, -1);
$bsp = preg_split('//', $b, -1);
$l1 = count($asp);
$l2 = count($bsp);
$length = $l1;
if ($l2 > $l1) {
$length = $l2;
}
$record = null;
$x = null;
for ($x = 0; $x < $length; $x++) {
if ($a[$x] != $b[$x]) {
if (!isset($a[$x])) {
$record.= $b[$x];
} else {
$record.= $a[$x];
}
}
}
echo $record;

Related

How to check if a given number is Fibonacci number?

i am trying to check my numbers is fibonacii or not ?
isFibonacci(13);
function isFibonacci( $testedNumber, $a = 1, $b = 1 )
{
if( $testedNumber == 0 || $testedNumber == 1 )
return true;//returning true for 0 and 1 right away.
$nextFib = $a + $b;//getting the next number in the sequence
if( $nextFib > $testedNumber )
return false;//if we have passed the tested number, it's not in the sequence
else if( $nextFib == $testedNumber )
return true;//if we have a perfect match, the tested number is in the sequence
else
isFibonacci( $testedNumber, $b, $nextFib );//otherwise, get the next fibonacci number and repeat.
}
<?php
function getFibonicciIndex($number)
{
$log_base = (1+sqrt(5))/2;
$index = log(($number*sqrt(5)-(1/2)), $log_base);
return floor($index)+1;
}
function getFibonicciNumber($term)
{
$a = (1+sqrt(5))/2;
$b = (1-sqrt(5))/2;
$fibonicci_number = (pow($a, $term)-pow($b, $term))/sqrt(5);
return $fibonicci_number;
}
$number = 14;
$index = getFibonicciIndex($number);
$index_value = getFibonicciNumber($index);
echo ($number == $index_value) ? "yes" : "no";
//This logic implements the best rule to find the Fibonacci series and their index. First we suppose the given no. is a part of Fibonacci series and try to get index .. and then for that given index we calculate the Fibonacci number and equate it to verify

In PHP, what does (int) really do?

I understand that casting with (int) rounds a number towards zero, but then I started poking around with bases other than 10 and now I'm not exactly sure what else (int) does:
$a = 050; // an octal number
echo $a; // output is ----> 40
however
$a = '050';
echo (int)$a; // output is ----> 50
So I thought (int) besides rounding towards zero also clips leading zeroes. But then if I do the same exercise as in the second code block (above) with binary I don't get what I expect:
$a = '0b010';
echo (int)$a; // output is ----> 0
and in hexadecimal:
$a = '0x050';
echo (int)$a; // output is ----> 0
Even using decimal scientific notation gives a quizzical result:
$a = 5e6;
$b = '5e6';
echo $a; // output is ----> 5000000
echo (int)$b; // output is ----> 5
What does casting to an integer using (int) really mean? Besides stripping the decimal point and everything after in a float, does (int) parse a cast string character-by-character, and return the concatenation of all leading, numeric, non-zero characters? Like this:
function intCast($str) {
$length = strlen($str);
$returnVal = '';
for($i = 0; $i < $length; $i++) {
// Note: ord() values 48 to 57 represent 0 through 9
if ($returnVal === '' && ord($str[$i]) == 48) {
continue; // leading zeroes are OK but don't concatenate
} else if (ord($str[$i]) > 48 && ord($str[$i]) < 58) {
$returnVal .= $str[$i];
} else {
break;
}
}
return (strlen($returnVal) > 0) ? $returnVal : 0;
}
***Note that this link does not seem to provide a sufficient answer.
'050' is a string, and PHP's first job in doing a typecast is to normalize that string:
echo '050' + 1 -> echo '50' + 1 -> echo 50 + 1 -> echo 51 -> 51
050 by itself is an octal number, it's already an integer, so the only thing PHP has to do is convert it to a base10 number for output:
echo 050 + 1 -> echo 40 + 1 -> echo 41 -> 41

PHP float comparison

I have the following PHP code in which I want to compare two decimal numbers. I have read in the PHP documentation that floating point numbers have limited precision.
$a = 0.0;
for ($i = 0; $i < 10; $i++) {
$a += 0.1;
}
var_dump($a);
echo gettype($a);
if ($a === 1.0) {
echo "IF";
} else {
echo "ELSE";
}
When I compare variable $a with 1.0, it always returns false, and the result will be 'ELSE'. My question is how I can get the code above working properly.
you can just do it this way:
//just a check if it is float, than round it to 1 decimal number and compare
if(is_float($a)){
echo 'not a float';
$a = round($a,1);
}
and output will be 'IF'
This question has been asked before, see Compare floats in PHP.
Basically you need to calculate the difference and see if it is small enough to be acceptable as "equal".
Try something like this:
$a = 0.0;
for ($i = 0; $i < 10; $i++) {
$a += 0.1;
$a=number_format($a,1);
//echo gettype($a);
//echo $a.'<br>';
if (floatval($a) === 1.0)
echo "IF";
else
echo "ELSE";
}
In order to make the comparison work I would truncate $a to one decimal place and format $a to a string with the required precision and compare it to "1.0".
To truncate $a I suggest reading this answer .
Or you can use $a as an integer. Them instead of incrementing by 0.1 use 1. And use 10 in the final comparison.

Checking repeating combination

So I have a program in PHP, which draws three numbers from array, adds them up and checks if sum = 10. If yes, then it should print those numbers on the display.
What I want to do is to check which combination was drawn. For example:
First draw: 1+7+2
Second draw: 5+4+1
Third draw: 1+2+7
First and third had the same numbers, so third shouldn't be shown. Unfortunately, I have no idea how to do it.
My code:
<?PHP
$numb = array(1,2,3,4,5,6,7,8,9,0);
$hm = count($numb);
for ($a=0; $a<$hm;$a++)
for ($b=0; $b<$hm;$b++)
for ($c=0; $c<$hm;$c++)
{
$cnt = $numb[$a]+$numb[$b]+$numb[$c];
if ($cnt == 10)
{
print_r ($numb[$a]);
echo "+";
print_r ($numb[$b]);
echo "+";
print_r ($numb[$c]);
echo "<br>";
}
}
?>
With the provided code, you can simply draw numbers "in order" to avoid duplicates:
$numb = array(0,1,2,3,4,5,6,7,8,9); // <-- must be sorted from lowest to highest
for ($a = 0; $a < $hm; $a++)
for ($b = $a; $b < $hm; $b++) // <-- start from $a
for ($c = $b; $c < $hm; $c++) // <-- start from $b
Thus, the combination 1+2+7 is possible, but not 1+7+2, and also not 7+1+2 etc.

Count from 3 in 3 until I reach 10 with php

I am trying a basic program to count from 3 in 3 until I reach 10. I tried:
<?php
$a = 0;
$b = 0;
while ($a < 10) {
$a += $b + 3;
echo "$a\n\r";
}
?>
The output is 3, 6, 9, 12. And the expected output would be 3, 6, 9. because I added < 10. Why is it doing this? Sorry for my noob question, but it's confusing: http://codepad.org/Y8yhd0JP
The value of $a is $a=9 in the 3rd iteration, so the loop will continue to go on to add upto 12.
To obtain the result as 3,6,9 check for while($a < 9){...}
<?php
$a = 0;
$b = 0;
while ($a < 9) {
$a += $b + 3;
echo "$a\n\r";
}
?>
This would be better to do with a do-while cycle, with $a initialised to its starting value before the cycle
<?php
$b = 0;
$a += $b + 3;
do {
echo "$a\n\r";
$a += $b + 3;
} while ($a < 10);
?>
The while will check if the value in $a is more than 10.
After the check you add to the value and print it, then check again, if its over 10, it will not do another loop.
So when it prints 12, it will have checked if $a was over 10, which is was not, cause it was 9. Then do the addition and echo and check again and exit.
To start with, note the $b is always 0, so you can eliminate it like this:
$a = 0;
while ($a < 10) {
$a += 3;
echo "$a\n\r";
}
Note that you change the value of $a between the test and the echo. That is probably the reason for your surprise.
A better way to write it would be
for ($a = 3; $a < 10; $a += 3) {
echo "$a\r\n";
}
An uglier solution:
$a = 0;
$b = 0;
while (($a += $b + 3) < 10)
echo "$a\n\r";
I moved the addition in the while loop. Here you dont't have to put the echo in {} because there's only one statement.
in your code you are printing the element after it is increased, so after it prints 9 , it checks the condition ($a < 10) , the condition is true so it proceeds and print 12 , while the next iteration the condition ($a < 10) fails and it stops. this is the reason , you can avoid it by changing your code as follows,
<?php
$a = 0;
$b = 0;
while ($a < 9) {
$a += $b + 3;
echo "$a\n\r";
}
?>
Hope it helps.

Categories