Check if variable is a number or array - php

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 !
}

Related

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';
}

PHP: using empty() for empty string?

I recently discovered this interesting article by Deceze.
But I'm a bit confused by one of its advises:
never use empty or isset for variables that should exist
Using empty() is not good choice to test if $foo = ''; is empty?
What he means is if you want to check if the string is empty then empty won't do that. Empty can mean false, 0, null. Anything 'falsy'.
E.g. these are all true:
<?php
$string = null;
if (empty($string)) {
echo "This is true";
}
$string = '';
if (empty($string)) {
echo "This is true";
}
$string = 0;
if (empty($string)) {
echo "This is true";
}
If you want to check if the string is an empty string you should do this check for '':
<?php
$string = '';
if (isset($string) && $string === '') {
echo "This is true";
}
$string = null;
if (isset($string) && $string === '') {
echo "This is false";
}
You should not use empty (or isset) if you expect $foo to exist. That means, if according to your program logic, $foo should exist at this point:
if ($foo === '')
Then do not do any of these:
if (isset($foo))
if (empty($foo))
These two language constructs suppress error reporting for undefined variables. That's their only job. That means, if you use isset or empty gratuitously, PHP won't tell you about problems in your code. For example:
$foo = $bar;
if (empty($føø)) ...
Hmm, why is this always true, even when $bar contains the expected value? Because you mistyped the variable name and you're checking the value of an undefined variable. Write it like this instead to let PHP help you:
if (!$føø) ...
Notice: undefined variable føø on line ...
The condition itself is the same, == false (!) and empty produce the same outcome for the same values.
How exactly to check for an empty string depends on what values you do or don't accept. Perhaps $foo === '' or strlen($foo) == 0 is the check you're looking for to ensure you have a string with something in it.
PHP's empty() can be used in many cases.
It works for checking:
if a string is blank
if a variable is undefined or null
And of course empty() is best for your case too.
Try using this php if function:
$retVal = (condition) ? a : b ;
where condition: $value == null
a: is the value to display if $value is null
b: is the actual value to display or any other value to be displayed when $value is not null
In case of further guidance, kindly comment

PHP compare strings error

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!

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.

Check if variable has a number php

I want to check if a variable has a number in it, I just want to see if there is one I don't care if it has any thing else in it like so:
"abc" - false
"!./#()" - false
"!./#()abc" - false
"123" - true
"abc123" - true
"!./#()123" - true
"abc !./#() 123" -true
There are easy ways of doing this if you want to know that is all numbers but not if it just has one. Thanks for your help.
You can use the strcspn function:
if (strcspn($_REQUEST['q'], '0123456789') != strlen($_REQUEST['q']))
echo "true";
else
echo "false";
strcspn returns the length of the part that does not contain any integers. We compare that with the string length, and if they differ, then there must have been an integer.
There is no need to invoke the regular expression engine for this.
$result = preg_match("/\\d/", $yourString) > 0;
Holding on to spirit of #Martin, I found a another function that works in similar fashion.
(strpbrk($var, '0123456789')
e.g. test case
<?php
function a($var) {
return (strcspn($var, '0123456789') != strlen($var));
}
function b($var) {
return (strpbrk($var, '0123456789'));
}
$var = array("abc", "!./#()", "!./#()abc", "123", "abc123", "!./#()123", "abc !./#() 123");
foreach ($var as $v) {
echo $v . ' = ' . b($v) .'<hr />';
}
?>
This should help you:
$numberOfNumbersFound = preg_match("/[0-9]+/", $yourString);
You could get more out of the preg_match function, so have a look at its manual
you can use this pattern to test your string using regular expressions:
$isNumeric = preg_match("/\S*\d+\S*/", $string) ? true : false;

Categories