If $var is empty dont work? - php

I run this code:
<?
$map = do_shortcode('[codepeople-post-map]');
if (empty($map)) {echo '<br />'; } else {echo $map;}
?>
The problem is when the $map is empty it won't echo the <br />
I have tried this 2 methods to see if $map is really empty:
echo $map; // It results empty and noting is shown on page.
var_dump($map); // It results: string(937) " "
My question is what does string(937) " " means and how can I make my code work?
I tried also:
<? if ($map == string(937) " ") {echo '<br />'; } else {echo $map;} ?>
But no success so far this last code is wrong and just gives error.

A variable is considered empty if it does not exist or if its value equals FALSE
Your variable is a string with a space, which evaluates to TRUE, so it is not empty.
Instead of using empty(), you might check if trim($map) === ''.

Well, it means that you have a string with a space in it.
Probably the var was previously a string which was emptied wrong. One solution I could suggest you, depending what your application's purpose is.
if(trim($map) == "" || $map == null)
{
echo "<br />";
}
else
{
echo $map;
}
Because actually it only means that the string contains a whitespace (this explains why there is a space in " "). You should try to locate where you get the $map value and try to put some verifications there.
Alex

Related

Booleon in objects (classes)

This is something I don't understand. If I assign the variable $bool the value true, and then later in the code change it to false, the variable $bool looses its value?
FYI: This reassignment of values is happening in a function in the class.
class csvcheck {
function booleonChange () {
echo "<br>";
$bool = true;
echo "1. assignment of booleon: " . $bool ."<br>";
$bool = false;
echo "2. assignment of booleon: " .$bool . "<br>"; // value of $bool is lost. Why??
}
}
$csv = new csvcheck;
$csv->booleonChange();
If this code is executed in the browser, you will see this:
assignment of booleon: 1
assignment of booleon:
If i remember correctly, the PHP boolean false is actually converted to an empty string rather than the value of 0 that I believe you are looking for.
Actually just looked for it, and this seems to confirm:
PHP printed boolean value is empty, why?

strcmp is not working expectedly in PHP

I am setting a session variable in a php file as:
$_SESSION['PageFrom']="check_login_test.php";
Later on the control is transferred to another php file via a form and post. The relevant code in the 2nd file is:
session_start();
$from=trim($_SESSION['PageFrom']);
pageFrom("check_login_test.php",$from);
die('I came here');
Now pageFrom is a function that should have compared the strings and said so. The original function was simply
function oldPageFrom($page,$from)
{
$page= trim($page);
$from=trim($from);
if (strcmp($page,$from)!==0)
{
echo 'The pages are not same';
}
}
Since it did not work as expected, I tried to debug the same and output as much as I can (This changed the old function, but now reveals some things interesting) . The function is
function pageFrom($page,$from)
{
echo '<br/>$page='.$page;
echo '<br/>$from='.$from;
$m=trim($page);
$n=trim($from);
echo "<br/>TrimmedPage=$m<br/>TrimmedFrom=$n";
$k= strcmp($m,$n);
echo '$k='.$k;
if($k !==0);
{
$i=strlen($from);
$j=strlen($page);
if ($i==$j)
{
echo "<br/>The string lengths are Equal $i=$j";
die('Equal in unequal');
}
else
{
echo "<br/>The string lengths are UnEqual $i<>$j";
die('UnEqual in unequal');
}
}
echo 'Works as expected. They are equal'; die('equal');
}
Strangely I get the following as output:
$page=check_login_test.php
$from=check_login_test.php
TrimmedPage=check_login_test.php
TrimmedFrom=check_login_test.php$k=0
The string lengths are Equal 20=20Equal in unequal
So the questions are:
(1)I have trimmed the strings. They are equal and of the same length. Strcmp returns 0. Then why does it enter the loop if($k !==0) at all? Note: no luck in ($k!=0) too.
You're using the following code:
if($k !==0);
{
The semi-colon (;) terminates the if clause and the subsequent { } block won't have any effect. Remove the ; after if and it will work as it should, i.e. this code below
if($k !==0)
{

Strugling with if, empty, and, or,

The following script should create an error when date_enabled is 2 and one of the three variables is empty. When day is empty for example, the script still doesn't echo the sentence.
Does anybody sees the problem?
$year = $_POST['date-year'];
$month = $_POST['date-month'];
$day = $_POST['date-day'];
$date_enabled = 2;
if ((($date_enabled ==2)) && ((empty($year) || empty($day) || empty($month)))){
echo "You didn't enter a valid date";
}
UPDATE - When I perform the following script it echos: its empty its empty (function). Which means that empty and the function isEmpty, which I created because of the advice of #Expert System , also works.
if (empty($day)){
echo "its empty";
}
if (!isset($day)){
echo "its not set";
}
if (isEmpty($day)){
echo "its empty (function)";
}
UPDATE AGAIN - The script above works indeed correctly. The problem lays with my form. It works fine now and thanks for your help.
I believe the definition of "empty" in your question is unclear. If empty in your question means zero-length string, then empty function is not the right one for you.
empty() definition from PHP doucment
Determine whether a variable is considered to be empty. A variable is
considered empty if it does not exist or if its value equals FALSE.
empty() does not generate a warning if the variable does not exist.
Maybe this custom function will work in your context
function isEmpty($var) {
return !isset($var) || ($var == '');
}
Then
if (($date_enabled == 2) &&
(isEmpty($year) || isEmpty($day) || isEmpty($month))){
echo "You didn't enter a valid date";
}
Try this code instead:
$year = isSet($_POST["date-year"]) ? $_POST["date-year"] : "";
$month = isSet($_POST["date-month"]) ? $_POST["date-month"] : "";
$day = isSet($_POST["date-day"]) ? $_POST["date-day"] : "";
$date_enabled = 2;
if ((($date_enabled ==2)) && ((empty($year) || empty($day) || empty($month)))){
echo "You didn't enter a valid date";
}
The problem might be the error of level E_NOTICE raised when you try to access an undefined index in $_POST array.
This shoukd notcause a problem (i.e. stop execution) with theususl/default configuration options, but with yours it might (just guessing).

Check for repeated elements in PHP array (if not empty)

Hi lets say I've got this array:
$check_post = array(
$_POST["a_post"],
$_POST["b_post"],
$_POST["c_post"],
$_POST["d_post"],
$_POST["e_post"],
$_POST["f_post"],
$_POST["g_post"],
$_POST["h_post"],
$_POST["i_post"]
);
I want to check whether any elements of this array are repeated, so the best I got is this:
if (count(array_unique($check_post)) < count($check_post))
echo "Duplicate";
else
echo "NO Duplicate";
Which works fine except for the fact that if more that one textarea is left blank (which is allowed) it gives me FALSE.
What I want is to NOT consider the empty values of the array for the (count(array_unique())
BTW I have tried with empty() and with array_values($check_post) but I cant get around it.
Thanks in advance!! please ask for any needed clarification.
To remove all the empty values from the comparison you can add array_diff():
if (count(array_unique(array_diff($check_post,array("")))) < count(array_diff($check_post,array(""))))
Well the way you have it is fine, though as you say, you have a need to remove the empty entries first.
$non_empty_check_post = array_filter($check_post, create_function('$item', 'return !empty($item);');
if (count(array_unique($non_empty_check_post)) < count($non_empty_check_post)) {
echo "Duplicate";
} else {
echo "NO Duplicate";
}
Filter out the blanks from your array:
function no_blanks($val) {
// Do not use empty() here if you don't consider the string "0" as blank
return trim($val) !== '';
}
$check_post = array_filter($check_post, 'no_blanks');
if (count(array_unique($check_post)) < count($check_post))
echo "Duplicate";
else
echo "NO Duplicate";
if (count(array_unique(array_filter(function(x) {return !empty(x)}, $check_post)) < count($check_post))
echo "Duplicate";
else
echo "NO Duplicate";

if(!empty) issues

What is wrong with this? The code in the "if statement" runs if $forwardformat isn't empty empty, but the "else" code doesn't run if $forwardformat is empty. Any ideas?!
while ($row = mysql_fetch_array($forwardresult)) {
$forward = $row["id"];
$forwardformat = str_replace(" ","",$forward);
if (!empty($forwardformat)) {
echo 'Exploring moves us <a href="casestudy.php?id=';
echo $forwardformat;
echo '">forward</a>';
}
else {
echo "forward";
}
}
see the list of thing that empty consider as empty
Returns FALSE if var has a non-empty and non-zero value.
The following things are considered to be empty:
■"" (an empty string)
■0 (0 as an integer)
■"0" (0 as a string)
■NULL
■FALSE
■array() (an empty array)
■var $var; (a variable declared, but without a value in a class)
It should indeed enter the if statement if $forwardformat isn't empty.
About the else statement, it only goes there if it is empty. So you might have to consider that $forwardformat is not empty. White spaces maybe ? Try to echo $forward between boundaries to be sure of that.
I think, your problem is this line:
$forwardformat = str_replace(" ","",$forward);
This only matches the space-character. Tab, Newline etc. are not replaced (and do not really show in your (html-)output when echoing the result. Thus i recommend, you try
$forwardformat = preg_replace('/\s+/','',$forward);
HTH
Argelbargel
Try this to investigate the contents of $forwardformat
while ($row = mysql_fetch_array($forwardresult)) {
$forward = $row["id"];
$forwardformat = str_replace(" ","",$forward);
if (!empty($forwardformat)) {
echo 'Exploring moves us forward';
//DEBUG
echo "<textarea>";
var_dump($forwardformat);
echo "</textarea>";
}
else {
echo "forward";
}
}
If you've got multi-byte string data (like with common UTF-8 encoding) in your db...
Check out mb_strlen()... compare it with strlen(), which should return 0 if its truly empty.

Categories