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.
Related
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!
I want to check if the content of a variable is an number or array. is_array(), is_int(), is_numeric() don't really work. Currently I'm using myArray[1] which seems to work. But I'm wondering why one of this function cannot do this for me?
Edit:
It seems that I had something like myArray['id'] as content and this always is an array.
$array = is_array(13) ? "yes" : "no";
$int = is_int(13) ? "yes" : "no";
$numeric = is_numeric(13) ? "yes" : "no";
echo $array."\n", $int."\n", $numeric."\n";
Replies with
no
yes
yes
As expected, so I'm not really sure what the issue is here!
It's perhaps worth noting that if you run:
$array = is_array("13") ? "yes" : "no";
$int = is_int("13") ? "yes" : "no";
$numeric = is_numeric("13") ? "yes" : "no";
echo $array."\n", $int."\n", $numeric."\n";
The response is:
no
no
yes
Which again is as you'd expect - a string and a number aren't represented as arrays.
Running gettype like this:
echo gettype(13);
shows it is an integer.
this is not a real question.
is_array() obviously returns false for the number 13
Got any real problem?
Though PHP can let you access numbers 1 and 3 from a variable contains number 13 using the same syntax used to access array members, it doesn't make an array out of integer. It is merely a "syntax sugar".
You have to verify your impressions before starting to write a question.
Are you sure?
$myNumber = 13;
$myArray = array("test" => "data");
if(is_array($myNumber)) {
echo "myNumber is an array!";
}else{
if(is_numeric($myNumber)) {
echo "myNumber is not an array, but it is a number!";
}
}
I get myNumber is not an array, but it is a number!
You can use gettype function.
$type = gettype($variable);
if ( $type == 'array' ) {
// it's an array
} else if ( $type == 'integer' ) {
// it's an integer
} else {
// it's a trap !
}
I am trying to get this:
if($a[2] > $b[2] && $c[2] < 3) echo "bingo";
But because the condition is retrieved from database, I need to get the whole condition into a variable and then somehow find a way to change the variable back into a condition. I thought it will be something along this line:
$condition = "$a[2] > $b[2] && $c[2] < 3";
$evaledCondition = eval("$condition;");
if($evaledCondition) echo "bingo";
Apparently it didn't work. Am I missing something?
eval() returns NULL unless return is
called in the evaluated code
$evaledCondition = eval("return $condition;");
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";
}
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))) {