PHP if condition with strings - php

I am trying to write would be a simple if condition.
function genderMatch($consumerid1, $consumerid2)
{
$gender1=getGender($consumerid1);
$gender2=getGender($consumerid2);
echo $gender1;
echo $gender2;
if($gender1=$gender2)
echo 1;
return 1;
else
echo 0;
return 0;
}
The output of the getGender function is either a M or F. However, no matter what I do gender1 and gender2 are returned as the same. For example I get this output: MF1
I am currently at a loss, any suggestions?

if ($gender1 = $gender2)
assigns the value of $gender2 to $gender1 and proceeds if the result (i.e. the value of $gender2) evaluates to true (every non-empty string does). You want
if ($gender1 == $gender2)
By the way, the whole function could be written shorter, like this:
function genderMatch($cid1, $cid2) {
return getGender($cid1) == getGender($cid2);
}

You have to put two == for comparison. With only one, as you have right now, you are assigning the value to the first variable.
if($gender1=$gender2)
would become
if($gender1==$gender2)

this:
if($gender1=$gender2)
should be
if($gender1==$gender2)
notice the extra ='s sign. I think you might also need curly brackets for multiple lines of an if/else statement.

Your using the assignment operator = instead of comparsion operators == (equal) or === (identical).
Have a look at PHP operators.

You have some structural problems with your code as well as an assignment instead of a comparison.
Your code should look like this:
function genderMatch($consumerid1, $consumerid2){
$gender1=getGender($consumerid1);
$gender2=getGender($consumerid2);
echo $gender1;
echo $gender2;
if($gender1==$gender2){
echo 1;
return 1;
}else{
echo 0;
return 0;
}
}
Notice the double '=' signs in the if statement. This is a comparison. A single '=' is an assignment. Also, if you want to execute more than 1 line of code with an if/else, you need brackets.

You are using a single = which sets the variable, ie. the value of $gender1 is set to be the value of $gender2.
Use the === operator instead: if($gender1 === $gender2). It is usually a good idea to do strict comparisons rather than loose comparisons.
Read more about operators here: php.net
Another alternative is to use strcmp($gender1, $gender2) == 0. Using a comparer method/function is more common in languages where the string-datatype isnĀ“t treated as a primary data-type, eg. C, Java, C#.

Related

Unexpected behaviour of "!print("1") || 1" in php

Example1:
if(!print("1") || 1){
echo "a";
}else{
echo "b";
}
Output
1b
The Example 1 is printing "1b" instead of "1a". According to me, inside if the final condition should be if(0 || 1) after solving !print("1").
But the Example 2 is printing "1a".
Example 2:
if((!print("1")) || 1){
echo "a";
}else{
echo "b";
}
Output
1a
Can you elaborate, why the or condition in the first statement didn't work.
The key thing here is to realise that print is not a function, and doesn't take arguments in parentheses - the parentheses aren't optional, they're just not part of the syntax at all.
When you write print("1"); the print statement has a single argument, the expression ("1"). That is if course just another way of writing "1" - you could add any number of parentheses and it wouldn't change the value.
So when you write print("1") || 1 the argument to print is the expression ("1") || 1. That expression is evaluated using PHP's type juggling rules as true || true which is true. Then it's passed to print and - completely coincidentally to what you were trying to print - is type juggled to the string "1".
The print statement is then treated as an expression returning true, and the ! makes it false, so the if statement doesn't run.
This is a good reason not to use parentheses next to keywords like print, require, and include - they give the mistaken impression of "attaching" an argument to the keyword.

Need exact reason for this logically condition failed

Why below code is printing the "here", it should be "there"
$a = "171E-10314";
if($a == '0')
{
echo "here";
}
else
{
echo "there";
}
PHP automatically parses anything that's a number or an integer inside a string to an integer. "171E-10314" is another way of telling PHP to calculate 171 * 10 ^ -10314, which equates to (almost) 0. So when you do $a == '0', the '0' will equate to 0 according to PHP, and it returns true.
If you want to compare strings, use the strcmp function or use the strict comparator ===.
when you use the == comparison, PHP tries to cast to different data types to check for a match like that
in your case:
'0' becomes 0
"171E-10314" is still mathematically almost 0 but I think PHP just rounds it to 0 due to the resolution of float.
check this link for a visual representation:
http://www.wolframalpha.com/input/?i=171E-10314
As per the answers given I tried to convert the string into numerical:
$a = "171E-10314" + 0;
print $a;
And I got output as 0.
Thats why it is printing here.
Use === /*(this is for the 30 character)*/

Exclamation mark in front of variable - clarification needed

I've been working with PHP for quite a while now, but this was always a mystery to me, the correct use of the exclamation mark (negative sign) in front of variables.
What does !$var indicate? Is var false, empty, not set etc.?
Here are some examples that I need to learn...
Example 1:
$string = 'hello';
$hello = (!empty($string)) ? $string : '';
if (!$hello)
{
die('Variable hello is empty');
}
Is this example valid? Would the if statement really work if $string was empty?
Example 2:
$int = 5;
$count = (!empty($int)) ? $int : 0;
// Note the positive check here
if ($count)
{
die('Variable count was not empty');
}
Would this example be valid?
I never use any of the above examples, I limit these if ($var) to variables that have boolean values only. I just need to know if these examples are valid so I can broaden the use of the if ($var) statements. They look really clean.
Thanks.
if(! $a) is the same as if($a == false). Also, one should take into account that type conversion takes place when using == operator.
For more details, have a look into "Loose comparisons with ==" section here. From there it follows, that for strings "0" and "" are equal to FALSE ( "0"==false is TRUE and ""==false is TRUE, too).
Regarding posted examples:
Example 1
It will work, but you should note, that both "0" and "" are 'empty' strings.
Example 2
It will work
It's a boolean tester. Empty or false.
It's the not boolean operator, see the PHP manual for further detail.

Operator not working

I have a operator in a string .
$c['operator'] = ">=";
if($sub_total.$c['operator'].$c['value'])
{
echo $sub_total.$c['operator'].$c['value'];
}
it obtain output is 20610>=30000
I'd put the possible operators in a switch:
$result = null;
switch($c['operator'])
{
case '>=':
$result = $sub_total >= $c['value'];
break;
case '<=':
$result = $sub_total <= $c['value'];
break;
// etc etc
}
This is far safer than using eval, and has the extra benefit that it sanitises the input.
$sub_total.$c['operator'].$c['value'] is not a comparison but a string concatenation. A filled string is always true in PHP, hence the if-statement is always true.
String can't be interpreted as php code unless you use eval (be careful with it).
What you are doing in your example in if statement is that you concatenate strings and because string after concatenation is not null it's evaluated to true, so if statement is executed.
In your case solution would be to see which operator is used like #adam has written in his solution.
BTW, having logic in strings (and possibly outside of script) is not a good idea.
Use PHP eval to evaluate the code you constructed.
$c['operator'] = ">=";
if(eval($sub_total.$c['operator'].$c['value']))
{
echo $sub_total.$c['operator'].$c['value'];
}
You can't do that in PHP, you should do something like below :
if ($c['operator'] == '>=' and $sub_total >= $c['value']) {
// Do something
} else if ($c['operator'] == '<=' and $sub_total <= $c['value']) {
// Do something else
} // etc...
Take a look at the eval method. It's very dangerous though
http://php.net/manual/en/function.eval.php

Finding common characters in strings

I am tring this method to find the common characters in two strings namely, $a and $r, but the first character isn't getting printed . Moreover the $already collects the common characters and prevents them from being printed for multiple times( I need each character to be printed once only) but it isn't doing so. Please tell me what errors I am making.
<?php
$a="BNJUBCI CBDIDIBO";
$r="SBKJOJLBOU";
$already="";
for($i=0;$i<strlen($r);$i++)
{
if (stripos($a,$r[$i])!=FALSE)
{
if (stripos($already,$r[$i])==FALSE)
{
$already=$already.$r[$i];
echo "already=".$already."<br>";
echo $r[$i]."<br>";
}
}
}
?>
Use !==FALSE instead of !=FALSE. The problem is that stripos returns 0 if the needle is at the start of the haystack, and 0 is falsy. By using !== you are forcing it to ensure the result is actually false, and not just 0.
This is actually listed in the docs. An "RTM" might be appropriate here.
Warning
This function may return Boolean FALSE, but may also return a non-Boolean value which evaluates to FALSE. Please read the section on Booleans for more information. Use the === operator for testing the return value of this function.
The simplest way to find the intersection of the two strings in PHP is to turn them into arrays and use the built-in functions for that purpose.
The following will show all the unique and common characters between the two strings.
<?php
$a="BNJUBCI CBDIDIBO";
$r="SBKJOJLBOU";
$a_arr = str_split($a);
$r_arr = str_split($r);
$common = implode(array_unique(array_intersect($a_arr, $r_arr)));
echo "'$common'";
?>
I would think a much simpler solution to this would be to make the strings into arrays and compare those no?
Something like:
<?php
$a="BNJUBCI CBDIDIBO";
$r="SBKJOJLBOU";
$shared = implode( '' , array_intersect( str_split($a) , str_split($r) ) );
?>
That should return you a string of all the characters in $a that are present in $r

Categories