if(!empty) issues - php

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.

Related

StrPos always returns False?

I've been working on a very basic search engine. It basically operates by checking if the word exists. If it does, it returns the link. I know most of you would suggest to create a database from phpMyAdmin but I don't remember the password to make the mySql_Connect command work.
Anyway here is the code:
<?php
session_start();
$searchInput = $_POST['search'];
var_dump($inputPage1);
var_dump($searchİnput);
$inputPage1 = $_SESSION['pOneText'];
$inputPage2 = isset($_SESSION['pTwoText']) ? $_SESSION['pTwoText'] : "";
$inputPage3 = isset($_SESSION['pThreeText']) ? $_SESSION['pThreeText'] : "";
if (strpos($inputPage1, $searchInput)) {
echo "True";
} else {
echo "False";
}
?>
When I search a word, any word from any page, weather it exists or not, it always returns false. Does anyone know why?
From the PHP documentation:
Warning: This function may return Boolean FALSE, but may also return a non-Boolean value which evaluates to FALSE. Please read the section on Booleans for more information. Use the === operator for testing the return value of this function.
So the function returns the integer 0 since $searchInput starts at the first character of $inputPage1. Since it is inside an if condition, that expects a boolean, the integer is then converted to one. When converted to boolean, zero is equal to false so instead the else block is executed.
To fix it, you need to use the !== operator (the not equal equivalent of ===):
if (strpos($inputPage1, $searchInput) !== false) {
//...
Try stripos() to match case insensitive
First print all items in $_POST and $_SESSION using
echo "<pre>";
print_r($_POST);
print_r($_SESSION);
and ensure that the search string really exist in the bigger string .
Also make sure that your are using "false" to compare :
i.e
$pos = strpos($biggerString,$seachString);
if($pos !== false)
{
echo "Not found";
}

Why won't PHP print 0 value?

I have been making a Fahrenheit to Celsius (and vise versa) calculator. All of it works just great, however when I try to calculate 32 fahrenheit to celsius it's supposed to be 0, but instead displays nothing. I do not understand why it will not echo 0 values.
Here is some code:
<?php
// Celsius and Fahrenheit Converter
// Programmed by Clyde Cammarata
$error = '<font color="red">Error.</font>';
function tempconvert($temptype, $givenvalue){
if ($temptype == 'fahrenheit') {
$celsius = 5/9*($givenvalue-32);
echo $celsius;
}
elseif ($temptype == 'celsius') {
$fahrenheit = $givenvalue*9/5+32;
echo $fahrenheit;
}
else {
die($error);
exit();
}
}
tempconvert('fahrenheit', '50');
?>
looks like $celcius has value 0 (int type) not "0" (string type), so it wont echoed because php read that as false (0 = false, 1 = true).
try change your code
echo $celcius;
to
echo $celcius."";
or
echo (string) $celcius;
it will convert your variable to string
when it printed nothing, could you have had a typo in the temptype 'fahrenheit'?
The code matches temptype, and if it's not F or C it errors out. Except that $error is not declared global $error; which uses a local undefined variable (you must not have notices enabled which would warn you), and undefined prints as the "" empty string.
die() is equivalent to exit(). Either function with the single parameter as an integer value of 0 indicates to PHP that whatever operation you just did was successful. For your function, if you want the value 0 output, you would want to use echo or print, not die() or exit().
Further, consider updating your function to return the value instead of directly outputting it. It will make your code more reusable.
More info about status codes here:
http://php.net/manual/en/function.exit.php
echo (float) $celcius;
This will do the work for you.

If $var is empty dont work?

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

Trying to remove an item from an array but it wont work

I dont really understand why this is not working, I am being returned to the correct header but the item is still in the array!
Here is the remove from array code:
<?php
session_start();
if ( !isset($_SESSION['username']) )
{
header("Location:loginform.php");
exit();
}
foreach ($_SESSION['list'] as $key => $disk)
{
if (($_SESSION['list'][$key]['bookisbn']) - ($_GET['bookisbn'])== 0)
{
unset($_SESSION['list'][$key]);
break;
}
}
header("Location: ".$_GET['location']);
exit();
?>
Thank you for any help you can offer
This is only a guess but the problem may lie in the fact that
$_GET['bookisbn']
is being treated as a string. Therefore if you cast it to an int
the if statement will return true removing the item from the
array.
Introduce this code:
// Casting the ISBN to an integer here
$bookISBN = (int) $_GET['bookisbn'];
if( ($_SESSION['list'][$key]['bookisbn'] - $bookISBN) == 0 ) {
// Unset item
}
I would listen to Artragis, but also try this:
You have parenthesis around each of the variables, but it's really the subtraction that has to equal zero. So, instead of:
if (($_SESSION['list'][$key]['bookisbn']) - ($_GET['bookisbn'])== 0)
{
unset($_SESSION['list'][$key]);
break;
}
Try:
if (($_SESSION['list'][$key]['bookisbn'] - $_GET['bookisbn']) == 0)
{
unset($_SESSION['list'][$key]);
break;
}
EDIT:
I would also cast both the Session and the GET variables as INTs, like one of the other posters mentioned, as well.
Try session_write_close() before the header. Perhaps is not saving.
You can also do this:
$mydata = $_SESSION['list'] ;
//do something with $mydata
$_SESSION['list'] = $mydata;
It will result in easier to read code, if you have other type of error, with this way you will not make the same mistake again.
You need to debug and test if line with unset is reachable.
You need to debug means you need to verify every program's step and every variable.
You need to test if line with unset is reachable means you have to echo something at the point of unset:
foreach ($_SESSION['list'] as $key => $disk)
{
var_dump("---\n",$_SESSION['list'][$key]['bookisbn'],$_GET['bookisbn']);
var_dump($_SESSION['list'][$key]['bookisbn'] - $_GET['bookisbn']);
var_dump($_SESSION['list'][$key]['bookisbn'] - $_GET['bookisbn'] == 0);
if ($_SESSION['list'][$key]['bookisbn'] - $_GET['bookisbn'] == 0)
{
unset($_SESSION['list'][$key]);
var_dump($_SESSION['list']);
break;
}
}
//comment out header to prevent moving out of page
#header("Location: ".$_GET['location']);
exit();
run this code and see if any of the values are wrong or unexpected.

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";

Categories