PHP compare strings error - php

I am a beginner in PHP and I am trying to separate the input based on the argument. Following is my code but it seems that my $arg variables is never set. Can someone point out my error?
$sender = $_GET['sender'];
$receiver = $_GET['receiver'];
$message = $_GET['message'];
$temp = explode( '.', $message);
$tempcnt = count($temp);
echo $temp[$tempcnt - 1];
if($tempcnt > 2)
{
if($temp[$tempcnt-1] === 'mp4')
{$arg = 3;}
elseif($temp[$tempcnt-1]==='jpg')
{$arg = 2;}
else
{$arg = 1;}
}
echo "Value of arg is" . $arg;
I have even tried with == and === and strcmp in if but still same issue.

Try This:
<?php
$temp strrchr("foo.jpg",".");
if($temp==".mp4")
$arg = 3;
elseif($temp==".jpg")
$arg = 2;
else $arg = 1;
?>

See also the other answers, but one possibility that hasn't been mentioned is that == and === and strcmp all compare case sensitively. So they won't find extensions like .MP4.
The solution in that case would be to use strcasecmp.
However, the first thing to do with problems like this is to output some more diagnostics, so that you can see for yourself what goes wrong. In this example, echo $tempcnt; after its assignment, or else echo "did nothing" after the outer if {..} block.
That way you'll be able to follow what the program flow is.

Issue was caused since i didn't realize i had compared for args > 2. Made it >=2 and viola it done!!
Thanks to #barmar for pointing that out!

Related

Is there any way to simplify this PHP code?

$a = $_POST['year'];
$b = $_POST['mileage'];
$c = is_numeric($a);
$d = is_numeric($b);
if ($c == False && $d == False) {
echo = "$c & $d variables are not numeric";
} else {
echo = "$c & $d variables are numeric";
}
This is a code that I whipped while learning PHP. Is there anyone that can help me simplify them. I don't like how it looked. I feel that it is too long. Beginner here (",)
Sometimes breaking down the way you set values can be useful, especially with complex calculations as it helps to debug the code.
But with simple assignments it is better (IMHO) to try and reduce the number of extra steps you make in your code. Setting a variable to then use it in another step is an overhead for both the computer (although negligible) but also adds extra lines of code. So assuming you just want to show if they are both numeric or not you can roll up all of those variables into the if statement...
if (is_numeric($_POST['year']) == False && is_numeric($_POST['mileage']) == False) {
echo "variables are not numeric";
} else {
echo "variables are numeric";
}
This does assume you have already checked that $_POST['year'] and $_POST['mileage'] are set (as does your code), you can use $_POST['mileage'] ?? '' if you want to make it more flexible.
Also the code only says the variables are not numeric if both values are not numeric. Change the && to || for either values not being numeric.

How to apply if condition when it's parameter is coming into a variable?

I have assigned a condition into a variable. Then I tried to put that variable as a parameter of a if statement. But the code is not working. Please check my code:
$a = 8;
$final_str = '$a == 10';
if($final_str) {
echo 'Output 1';
} else {
echo 'Output 2';
}
The desired output should be Output 2. But it is not working. I always see Output 1. Please help me in this case.
Thanks in advance!
As per your request, the real problem here is this line of code:
$final_str = '$a == 10';
Although you have said that you cannot change the first two lines of code as it is what you have intended, I think that what you have intended and the result of this are two different things.
You see, you are defining '$a == 10' which is interpreted literally as a string value.
So you are trying to do something like:
if ('some string') ...
The result of this is true because a string that is not empty is a truthy value.
I think your intention however, was to test if the variable $a is equal to the integer value of 10?
In which case you actually need to do:
$final_str = $a == 10;
The result of this can be true or false depending on whether the variable $a is equal to 10 or not, that way your if condition will reflect the desired result?
EDIT:
If however you are trying to create some PHP code dynamically within your string you'd need to run it through eval and here is more information relating to the usage.
EDIT 2:
I would rather try to re-factor this into something more like:
$thisPage = 8;
$truthyPages = array(10,20);
if (in_array($thisPage,$truthyPages)) {
echo 'positive output';
} else {
echo 'negative output';
}
Or maybe even:
$a = 8;
// Step 1
$final_result = $final_result || $a == 10;
// Step 2
$final_result = $final_result || $a == 20;
if ($final_result) {
echo 'success';
} else {
echo 'failure';
}

Problems determing if value is a number

I am doing this check on a variable:
if (empty($num) || !isset ($num) || !is_numeric ($num))
{
$population = -1;
}
else
{
$population = $num;
}
And what I was hoping for is that if num is null or not a number or doesn't exist, to make $population = -1 and in all other cases to give $population the value of $num
But that is not happening for me. Any ideas why this isn't working the way I thought it would?
Is this possibly an issue with scoping?
<?php
$num=23;
tryStuff();
function tryStuff(){
global $num; //if this line is commented out, then -1 is printed.
if (empty($num) || !isset ($num) || !is_numeric ($num))
{
$population = -1;
}
else
{
$population = $num;
}
echo "$population<br>";
}
?>
is_numeric should work good by itself. If instead of $num the value was a super global, using isset would be a good idea to avoid warnings:
$population = is_numeric ($num) ? $num : -1;
// or
$population = isset($_GET['num']) && is_numeric($_GET['num']) ? $num : -1;
post an example of $num
using regex:
$population = preg_match("/^\d+$/", $num) ? $num : -1;
I'm going to go out on a limb here and say that you're inputting the number 0 and getting unexpected results, because empty(0) is true.
I think if you change your code to:
if (!isset ($num) || !is_numeric ($num))
{
$population = -1;
}
else
{
$population = $num;
}
You will get the desired results.
EDIT Possibly you are looking for an Integer or a Float in which case you should replace is_numeric with is_int or is_float respectively.
Why not flip it around and go with a positive as a primary check?
$population = (isset($num) && is_numeric($num)) ? $num : -1;
I've never had fun with negative's and "or" statements :)
What happens if you var_dump($num);?
Personally, my guess is that PHP is interpreting something input as a number, when you are expecting it to be a string. Such examples might include things which might accidentally convert, like '0xFF' (a string of the Hex for 255).
Clearly the issue is not about isset, because if it were, you would have caught it, and you said to evolve that this happens even without empty. This means that something which you are expecting to be is_numeric($num) === FALSE can be evaluated as TRUE.

$_GET value or eregi error?

I'm not sure where is my problem. I've a script called with parameters (GET) like :
http://www.xxx.com?isms_restemsg=STOP&value=1
Here is my code :
$keyword_allowed = array("STOP", "");
$found_keyword = "N";
$keyword_cf = "";
for($i=0; $i < 2; $i++)
{
if (eregi($keyword_allowed[$i], $_GET["isms_restemsg"]))
{
$found_keyword = "Y";
$keyword_cf = $keyword_allowed[$i];
}
}
QUESTION : what happend when the url invoked is :
http://www.xxx.com?isms_restemsg=&value=1
In this case, what happend at the eregi instruction.
I'm asking this question because the $found_keyword="N", it should be "Y" Or is there an error ?
If yes can you help me ?
eregi is depreciated as of php 5.
Use stristr instead
if (stristr($keyword_allowed[$i], $_GET["isms_restemsg"]))
Or better yet, array_search
$keyword_allowed = array("STOP", "");
$found_keyword = "N";
if(($keyword_c = array_search($_GET["isms_restemsg"], $keyword_allowed)) !== false) {
$found_keyword = "Y";
}
You shouldn't use eregi(), since it's deprecated.
It doesn't even look as if you need regular expressions after all.
Give it a try with stristr() or even simple compare syntax:
if ($keyword_allowed[$i] == $_GET["isms_restemsg"])
(If you write this yourself you probably have control over the GET values as well.)
You can help yourself in such cases by echoing some debug output:
print_r($_GET);
for($i=0; $i < 2; $i++)
{
echo eregi($keyword_allowed[$i], $_GET["isms_restemsg"]));
}
When the URL is like this
http://www.xxx.com?isms_restemsg=&value=1
Your $_GET["isms_restemsg"] is blank
hence if (eregi($keyword_allowed[$i], $_GET["isms_restemsg"]))
second argument is passed as null in eregi function
eregi is deprecated stop using it replace with preg_match
I'm not quite sure yet, but there are probably other ways to achieve what you are trying to do.
First you could use a more specific regular expression to get rid of the loop. This checks for two alternatives, STOP and the empty string (this is probably what failed with your eregi test).
if (preg_match('/^(STOP | )$/ix', $_GET["isms_restemsg"], $r))
{
$found_keyword = "Y";
$keyword_cf = $r[0];
}
else {
$found_keyword = "Y";
}
Or since you only need to check against two values:
if (in_array(strtoupper($_GET["isms_restemsg"]), array("STOP", "")) {
$found_keyword = "Y";
}

Strange IF Statement behaviour

I have an IF statement that consists of two separate function calls
passing values to two variables. Obviously if neither value is 'FALSE'
then the code block is executed:
<?php
class MyValidater {
static function validateString($string) {
if (preg_match("/[A-Za-z]+/", $string)) {
return $string;
} else {
return false;
}
}
}
$firstName = "Daniel";
$surname = "Simmons";
// Dodgy IF statement
if ($first = MyValidater::validateString($firstName) && $second = MyValidater::validateString($surname)) {
print("Success: $first $second");
} else {
print("Fail: $first $second");
}
?>
As you can see both the $first and $second variables should contain
the values held in $firstName and $surname after successfully being
validated by the Static method validateString.
However, the values of the two variables end up: $first = '1' and
$second = "Simmons".
The '1' should be "Daniel" but for some reason $first is being passed
the value '1' or TRUE. If you swap the two assignment statements over
so that $second is evaluated first, you end up with the opposite
outcome as before. $second = '1' and $first = "Daniel"
Can anyone explain why the String value "Daniel" being returned from
the class method is being changed into the int '1' for the first part
of the conditional statement only? I have had a quick look though the
PHP documentation but cannot find an explanation.
For the moment the workaround is to change the return value from the
static method to be true/false and then make $first = $firstName,
etc... upon success. But this involves more code and I would rather
find out why this way does not work.
You need to bracket your expressions:
if (($first = MyValidater::validateString($firstName)) && ($second = MyValidater::validateString($surname)))
What's actually happening is this:
if ($first = (MyValidater::validateString($firstName) && $second = MyValidater::validateString($surname)))
It would be much clearer to just do this (note this code isn't identical to what you have):
$first = MyValidater::validateString($firstName);
$second = MyValidater::validateString($surname);
if ($first && $second)
&& is higher then = in the operator precedence. add brackets and it will work.
http://www.php.net/manual/en/language.operators.precedence.php
you can read about operator precedence here.
Also, setting values inside of an if condition is usually bad practice. If you add the brackets, you will most probably see why (let $first set to false and $second set to a string) => the first will be evaluated, but since it is false then, it won't process further since it will go to the else anyways. => second will not be set correct if first = false.
Try using parenthesis
($first = MyValidater::validateString($firstName)) && ($second = MyValidater::validateString($surname)))
First is getting the result of the first function call AND the second function having a value.
= is for attributions
== is for comparisons, the data type doesn't matter
=== is for comparisons, the data type matters
What is happening is that PHP is assigning $first with “MyValidater::validateString($firstName)) && $second = MyValidater::validateString($surname)”
You need brackets around first compare and second, like this.
if ( ($first = MyValidater::validateString($firstName)) && ($second = MyValidater::validateString($surname))) {

Categories