Boolean from MySQL to PHP - Conversion to tinyint and comparing - php

My database has multiple boolean values. After I saved the database, the booleans got converted into tinyint(1). I think this is because it just needs to save 1 or 0.
However, I now have a problem comparing the value in PHP. I saved the tinyint into an array without any code-wise conversion. The array has multiple entries that are text and date and multiple entries with booleans, for example:
array[0] is '09:45:00'
array[1] is '10:45:00'
array[2] is 1
array[3] is 0
array[4] is 0
array[5] is 1
array[6] is 'active'
Now if I loop through the array I want to check if the value is a time, a text, or true/false.
Checking if the entry is true will always return true, because no entry is empty. Checking if the entry is 1 or 0 works for the boolean, but when I check if 'active' == 0 it is returning true. Why is this the case and how can I get a false if I compare a string with a tinyint?
Comparing with === does not work in any case.

I think u can do this with some nested if-else statements. But I'm pretty sure there is a better-looking solution too. :)
$a=array('09:45:00','10:45:00',1,0,0,1,'active',3.12);
foreach ($a as $value) {
$type= gettype($value);
if ($type == "string") {
if(strtotime ($value)){
echo "$value is 'Time' \n";
}
else{
echo "$value is 'String' \n";
}
} elseif ($type == "integer") {
if($value == 0 || $value == 1){
echo "$value is 'Boolean' \n";
}
else{
echo "$value is 'Integer' \n";
}
} else{
echo "$value is ($type)!";
}
}

Related

Determine Difference Between NULL, ZERO (double) and value (double)

As both NULL and 0 return as empty in php, I'm struggling to determine the difference based on double type results from a mysqli recordset.
I've tried converting each scenario in order to return a more manageable returned string:
if($val == 0){
echo "No Cost Option";
} elseif (empty($val)){
echo "UNCOSTED";
} else {
echo "£ ".number_format($val ,2);
}
Theoretically, if a zero is present in the DB, it should return "No Cost Option".
Equally then, if the DB comes back with NULL, it should return "UNCOSTED".
Finally, if there is a value, it will simply format that value.
Currently (and incorrectly), both NULLs and 0s are being treated the same way so both get processed as "No Cost Option".
You can strictly compare to null. If you strictly compare to integer it might not work, because the result would be a numeric string.
Reverse your if statement order and check for null first.
if (null === $val) {
echo "UNCOSTED";
} elseif ($val == 0) {
echo "No Cost Option";
} else {
echo "£ ".number_format($val, 2);
}
If you strictly want to compare to the number 0 your should use ===
if($val === 0){
echo "No Cost Option";
} elseif (empty($val)){
echo "UNCOSTED";
} else {
echo "£ ".number_format($val ,2);
}
You use === to get a strict identical comparison (Type & value).
If you want more precision,
0, null, false, "0", [] (an empty array) and more (see type comparaison) are equal in value.
So
0 == null == false == "0" == array()
But they are not if you compare they type with ===

How to check if an associative array has an empty or null value

In the following associative array
$array = array(
[0] => 0
[1] => 1
[2] =>
[3] => 2
[4] =>
)
how can you determine if a given key has an empty (or null) value? I used
if(empty($array[$value]))
and
if(isset($array[$value])) && $array[$value] !=='')
When using empty I also get false for the first array value which is zero and isset doesn't seem to do the trick.
use array_key_exists() and is_null() for that. It will return TRUE if the key exists and has a value far from NULL
Difference:
$arr = array('a' => NULL);
var_dump(array_key_exists('a', $arr)); // --> TRUE
var_dump(isset($arr['a'])); // --> FALSE
So you should check:
if(array_key_exists($key, $array) && is_null($array[$key])) {
echo "key exists with a value of NULL";
}
Looked at all the answers and I don't like them. Isn't this much simpler and better? It's what I am using:
if (in_array(null, $array, true) || in_array('', $array, true)) {
// There are null (or empty) values.
}
Note that setting the third parameter as true means strict comparison, this means 0 will not equal null - however, neither will empty strings ('') - this is why we have two conditions. Unfortunately the first parameter in in_array has to be a string and cannot be an array of values.
PHP empty return values states:
Returns FALSE if var exists and has a non-empty, non-zero value. Otherwise returns TRUE.
The following things are considered to be empty:
"" (an empty string)
0 (0 as an integer)
0.0 (0 as a float)
"0" (0 as a string)
NULL
FALSE
array() (an empty array)
$var; (a variable declared, but without a value)
From your array example I take it as you want to exclude the 0 as an integer. If that's the case this would do the trick:
<?php
$array = array(0, 1, '', 2, '');
foreach ($array as $value) {
echo (empty($value) && 0 !== $value) ? "true\n" : "false\n";
}
If you want to exclude other conditions that empty considers just negate them in that condition. Take in account that this might not be the optimal solution if you want to check other values.
if ( !isset($array[$key]) || $array[$key] == "" || is_null($array[$key]) )
{
//given key does not exist or it has "" or NULL value
}
foreach($array as $i => $v) {
if(null === $v) {
// this item ($array[$i]) is null
}
}
...or, for a given key:
if(null === $array[2]) {
// this item ($array[2]) is null
}
Potentially this could be cleaner if I knew how the array was constructed, but, having the assumption that you can have both empty strings, or nulls in the array, and you want to account for values of 0 --> here's what I'd do:
if (is_null($array[$key]) || (string)$array[$key] == '')
Here's a little bit of test code showing it in action with an array that has both 0, null, an empty string, and non-zero integers...
$array = array(0,1,null,2,'');
print_r($array);
foreach ($array as $key => $val) {
if (is_null($array[$key]) || (string)$array[$key] == '') {
echo $key.", true\n";
}
}
As for using isset() -- an empty string is consider to be set. Which may be what you're running into (aside from 0 being considered empty) Compare with this usage:
$foo = array(0,1,null,2,'');
print_r($foo);
foreach ($foo as $key => $val) {
if (isset($foo[$key])) {
echo $key.", true\n";
}
}
function is_empty($data){
$is_empty = true;
foreach ($data as $val){
if(is_array($val)){
$is_empty = is_empty($val);
}else{
if(!empty($val)){
$is_empty = false;
break;
}
}
}
return $is_empty;
}

PHP If Statement not working correctly, not null

I'm struggling to understand why my if statement below always results in false. I am creating a function which will test incoming connections to a script which will reject connections made by certain bots.
In my test below, on applying the if logic, I'm expecting a TRUE as both the array $value and $test value should match... resulting in a NOT NULL?
$bots = array(0 => "PaperLiBot", 1 => "TweetmemeBot", 2 => "Appsfirebot", 3 => "PycURL", 4 => "JS-Kit", 5 => "Python-urllib");
$test = strtolower("PaperLiBot");
foreach($bots as $value)
{
$i = strtolower(strpos($value, $test));
if ($i != NULL)
{
echo "Bot is found";
exit;
}else
{
echo "not found";
}
}
I think you are trying to accomplish this
foreach($bots as $value)
{
$i = strpos(strtolower($value), $test);
if ($i !== false){
echo "Bot is found";
exit;
}else{
echo "not found";
}
}
you want to write:
if(stristr($value, $test)){
// found
}else{
// not found
}
null in PHP is mutually type-castable to '0', '', ' ', etc... You need to use the strict comparisons to check for a 0-based array index:
if ($i !== NULL) {
...
}
note the extra = in the inequality operator. It forces PHP to compare type AND value, not just value. When comparing value, PHP will typecast however it wants to in order to make the test work, which means null == 0 is true, but null === 0 is false.
the correct way to check if a variable is set to NULL is:
if(!is_null($var)){
[my code]
}
the strpos returns a boolean, not a NULL value.
if you are unsure of the content of a variable, you can always debug it with a simple
var_dump($var);

PHP Associative array

I have an array as
$arrTest = array('val1','val2','val3','val4');
$arrTest['lastKey'] = 'Last Key';
foreach($arrTest as $key => $val) {
if($key == 'lastKey') {
echo "last found";
}
}
The above code is not working. I have added associative element in the array. Could it be the reason?
Change == to === in:
if($key == 'lastKey')
Your existing code echos last found twice, once for key 0 and once for key lastKey.
Comparing integer 0 and string 'lastKey' using == returns true !!
From the PHP manual:
String conversion to numbers
When a string is evaluated in a
numeric context, the resulting value
and type are determined as follows.
The string will be evaluated as a
float if it contains any of the
characters '.', 'e', or 'E'.
Otherwise, it will be evaluated as an
integer.
The value is given by the initial
portion of the string. If the string
starts with valid numeric data, this
will be the value used. Otherwise, the
value will be 0 (zero). Valid numeric
data is an optional sign, followed by
one or more digits (optionally
containing a decimal point), followed
by an optional exponent. The exponent
is an 'e' or 'E' followed by one or
more digits.
Use === to compare. Because when key 0 will be compared with string lastKey, string will be converted to integer and false result will be returned.
http://codepad.org/5QYIeL4f
$arrTest = array('val1','val2','val3','val4');
$arrTest['lastKey'] = 'Last Key';
foreach($arrTest as $key => $val) {
if($key === 'lastKey') {
echo "last found";
}
}
Read more about differences: http://php.net/manual/en/language.operators.comparison.php
You need to change your equality condition to check the type as well.
if($key === 'lastKey')
This is because PHP evaluates ' ' == 0 as true.
When I ran your code, 'last found' was outputted twice. 'lastKey' is evaluated to 0 in PHP, so if($key == 'lastKey') actually matches twices: once for 0 and once for your special element.
use the end() function to get the last key of an array and compare it in your if statement.
$arrTest = array('val1','val2','val3','val4');
$lastKey = end($arrTest);
foreach($arrTest as $key => $val) {
if($val == $lastKey) {
echo "last found";
}
}
Your code is working fine :
see it here : http://codepad.org/hfOFHMnc
However use "===" instead of "==" as you might encounter a bug when
comparing the string with 0 , and it will echo twice.
<?php
$arrTest = array('val1','val2','val3','val4');
$arrTest['lastKey'] = 'Last Key';
print_r($arrTest);
foreach($arrTest as $key => $val) {
if($key == 'lastKey') { // use === here
echo "key = $key :: last found \n";
}
}
If you want to test if an array key exists, simply use array_key_exists:
array_key_exists('lastKey', $arrTest)
You could also use isset but note that it returns false if the value associated to the key is null.

php, mysql, arrays - if( x == 0 ) { }

I have the following code
while($row = $usafisRSP->fetch_assoc())
{
$hidden_keys = array('Applicantid', 'unique_num', 'regs_time' ....);
$hidden_fields = array_intersect_key($row, array_fill_keys($hidden_keys, NULL));
$hidden_values = array();
foreach ($hidden_fields as $key => $value) {
// fill the values array using the values from fields array
$hidden_values[$value] = "$key = ".base64_decode($value)."";
if(base64_decode($value)== 0)
{
$hidden_values[$value] = "";
}
echo $hidden_values[$value];
The question is about "if($hidden_values[$value] == 0)" ... Basically I want to do not display/echo the $hidden_values[$value] if it's value of $value is 0. Sometimes $value is 0 or some words like (23 avenue).
I think you ran into three catches with PHP type comparisons and equalities:
Any string not beginning with a number will always loosely equal 0. So basically, if(base64_decode($value)== 0) will likely always resolve to true, even if decoded $value is "Adam".
Return value of base64_decode is a string, so if 0 is the result, it will be string 0, not integer 0. This means if(base64_decode($value) === 0) wouldn't even work if decoded $value is "0". Another catch is base64_decode may return false on errors, again failing this strict equality check.
A non-empty string (other than "0") will always loosely equal true. So this is the only comparison you really need for your case.
I think this is what you want, replacing the last 5 lines...
if(base64_decode($value)) echo $hidden_values[$value];
else $hidden_values[$value] = "";
} // closing your for loop
Is this what you're looking for?
foreach( $hidden_values as $value ) {
if( $value !== 0 ) {
echo $value;
}
}

Categories