set array has no counted elements - php

Just learned PDO today and in the middle of making a twitter clone to learn using PHP/MySQL.
Here's a snippet of a code that is supposed to show all the tweets in the database under a certain user_id (kind of like the twitter feed).
<?php
$all_tweets = showtweets($pdo, $_SESSION['user_id']);
if (count($all_tweets)) {
foreach($all_tweets as $key => $value) {
?>
<div class="tweet">
<?php
echo $key['tweet'] . "<br>
Written By: " . $_SESSION['user_id'] . " on " . $key['time'] . "<br>";
?>
</div>
<?php
};
} else {
echo "You haven't posted anything yet!";
};
?>
Here's the function showtweets in my php code
function showtweets($pdo, $user_id) {
$show_tweets_stmt = "SELECT tweet, time FROM tweets WHERE id=:user_id
ORDER BY time DESC";
$show_tweets = $pdo->prepare($show_tweets_stmt);
$show_tweets->bindParam(':user_id', $_SESSION['user_id']);
$show_tweets_execute = $show_tweets->execute();
if (!$show_tweets_execute) {
printf("Tweets failed to be retrieved! <br> %s", $pdo->error);
} else {
$tweets_array = $show_tweets->fetchAll();
return $tweets_array;
};
}
I tried running isset($all_tweets) and it returned true, while echoing count($all_tweets) printed 0.
I think something is wrong with my addtweets function code, and I've been dabbling with this all day but I can't get it to work.
Any advice? Much thanks

From PHP, isset:
Returns TRUE if var exists and has value other than NULL, FALSE
otherwise.
So, in your case, the variable $all_tweets has been set, and the value is not NULL.
More specifically, your issue lies in how you determine if an array is empty to begin with.
To determine if $all_tweets is empty in PHP - the internet, and (mainly) a lot of StackOverflow posts strongly suggest using empty(), which (from the PHP docs):
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)
Also, for more reading on the matter, examine this:
How to check whether an array is empty using PHP?

If you want to see if an array is empty or not use empty($array) isset($array) returns true because there is an empty array exist.

Related

How to check the query string of my current url for a specific key-value pair?

How I can identify in PHP if my current URL contains this text special_offer=12.
For example, if my domain URL is http://www.example.com/newproducts.html?special_offer=12 then echo something.
Alternatively, the domain can be http://example.com/all-products.html?at=93&special_offer=12
This text will always be the same: special_offer=12.
You can access the Query parameters using the $_GET superglobal, In this case:
if(isset($_GET['special_offer']) && $_GET['special_offer'] == 12){
echo "Something";
}
if (isset($_GET['special_offer'] {
do something...
}
Write var_dump($_GET);
to see how superglobal $_GET works
Just by checking the $_GET var ?
if(!empty($_GET["special_offer"]) && $_GET["special_offer"] ==12 ){
//You're code here
}
You Can Access To Query Parameter Using Get Like This:
if(isset($_GET['special_offer'] == 12)){
//echo " ECHO YOUR CODE HERE ";
}
OR
NOTE: Avoid To Use isset() and USE !empty() ..Because isset() accept the null value also to store , So avoid to use it !!
if(!empty($_GET['special_offer']) && $_GET['special_offer'] == 12){
//echo " ECHO YOUR CODE HERE ";
}
NOTE:
Empty checks if the variable is set and if it is it checks it for null, "", 0, etc
1 Isset just checks if is it set, it could be anything not null
2 With empty, the following things are considered 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 $var; (a variable declared, but without a value in a class)
Reference: http://php.net/manual/en/function.empty.php

empty() not working in PHP

I am working with PHP 5.4 and I am submitting a form via POST request, and I want to check to see if one of the values is null, or populated. However the condition does not appear to resolving to true and I can't figure out what I'm doing wrong.
Here is the code:
$route = $_POST['route'];
echo ("route: " . $route);//this is displaying 'route:null'
if(empty($route))
{
echo ("route2: " . $route);
}
I have also tried to use isset is_null and $route === null $route == null
None seem to work .
I have also tried inserting true into the if statement to make sure that true is resolving correctly, but it does.
If the echo is displaying null then it is not null. It is a string "null" which are two entirely different things.
This, in fact is a common problem when using javascript to post to php. Javascript's null gets converted to string when posting to php, thus passing all checks (empty(), isset(), ...).
The easiest way to see these issues is to do a var_dump($_POST), which will give you exactly what you have received in your post.
In your case you are receiving string "null", which in no way can pass the empty() check. You either need to check if $route=="null" or fix your javascript so it does not send null values.
Fixing javascript is the proper way to go.
The POST variable does not contain anything. Either it does not exist on the form or you have it misspelled.
According to the docs null is empty.
http://us3.php.net/empty
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)
Empty - 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.
How about try using (or adding):
if(is_null($route))
or
if(!isset($route))
if( isset($_POST['route']) && !empty($_POST['route']) ) {
$route = $_POST['route'];
echo "Route: $route";
} else {
echo "Route: None specified";
}
Because the $_POST is returning null as a string I had to do this:
$route = $_POST['route'];
echo ("route: " . $route);
if($route == 'null')//surround null in quotes
{
echo ("route2: " . $route);
}
Try This ;)
function convert_null($data)
{
$data = str_replace(null,"",$data);
$data = str_replace("null","",$data);
$data = trim($data);
return $data;
};
convert_null($route);
if(empty($route))
{
echo ("route2: " . $route);
};

Checking for a null value in conditional in PHP

I have found there to be multiple ways to check whether a function has correctly returned a value to the variable, for example:
Example I
$somevariable = '';
$somevariable = get_somevariable();
if ($somevariable)
{
// Do something because $somevariable is definitely not null or empty!
}
Example II
$somevariable = '';
$somevariable = get_somevariable();
if ($somevariable <> '')
{
// Do something because $somevariable is definitely not null or empty!
}
My question: what is the best practice for checking whether a variable is correct or not? Could it be different for different types of objects? For instance, if you are expecting $somevariable to be a number, would checking if it is an empty string help/post issues? What is you were to set $somevariable = 0; as its initial value?
I come from the strongly-typed world of C# so I am still trying to wrap my head around all of this.
William
It depends what you are looking for.
Check that the Variable is set:
if (isset($var))
{
echo "Var is set";
}
Checking for a number:
if (is_int($var))
{
echo "Var is a number";
}
Checking for a string:
if (is_string($var))
{
echo "var is a string";
}
Check if var contains a decimal place:
if (is_float($var))
{
echo "Var is float";
}
if you are wanting to check that the variable is not a certain type, Add: ! an exclamation mark. Example:
if (!isset($var)) // If variable is not set
{
echo "Var Is Not Set";
}
References:
http://www.php.net/manual/en/function.is-int.php
http://www.php.net/manual/en/function.is-string.php
http://www.php.net/manual/en/function.is-float.php
http://www.php.net/manual/en/function.isset.php
There is no definite answer since it depends on what the function is supposed to return, if properly documented.
For example, if the function fails by returning null, you can check using if (!is_null($retval)).
If the function fails by returning FALSE, use if ($retval !== FALSE).
If the function fails by not returning an integer value, if (is_int($retval)).
If the function fails by returning an empty string, you can use if (!empty($retval)).
and so on...
It depends on what your function may return. This kind of goes back to how to best structure functions. You should learn the PHP truth tables once and apply them. All the following things as considered falsey:
'' (empty string)
0
0.0
'0'
null
false
array() (empty array)
Everything else is truthy. If your function returns one of the above as "failed" return code and anything else as success, the most idiomatic check is:
if (!$value)
If the function may return both 0 and false (like strpos does, for example), you need to apply a more rigorous check:
if (strpos('foo', 'bar') !== false)
I'd always go with the shortest, most readable version that is not prone to false positives, which is typically if ($var)/if (!$var).
If you want to check whether is a number or not, you should make use of filter functions.
For example:
if (!filter_var($_GET['num'], FILTER_VALIDATE_INT)){
//not a number
}

Check whether an array is empty [duplicate]

This question already has answers here:
How to check whether an array is empty using PHP?
(24 answers)
Closed 7 years ago.
I have the following code
<?php
$error = array();
$error['something'] = false;
$error['somethingelse'] = false;
if (!empty($error))
{
echo 'Error';
}
else
{
echo 'No errors';
}
?>
However, empty($error) still returns true, even though nothing is set.
What's not right?
There are two elements in array and this definitely doesn't mean that array is empty. As a quick workaround you can do following:
$errors = array_filter($errors);
if (!empty($errors)) {
}
array_filter() function's default behavior will remove all values from array which are equal to null, 0, '' or false.
Otherwise in your particular case empty() construct will always return true if there is at least one element even with "empty" value.
You can also check it by doing.
if(count($array) > 0)
{
echo 'Error';
}
else
{
echo 'No Error';
}
Try to check it's size with sizeof if 0 no elements.
PHP's built-in empty() function checks to see whether the variable is empty, null, false, or a representation of zero. It doesn't return true just because the value associated with an array entry is false, in this case the array has actual elements in it and that's all that's evaluated.
If you'd like to check whether a particular error condition is set to true in an associative array, you can use the array_keys() function to filter the keys that have their value set to true.
$set_errors = array_keys( $errors, true );
You can then use the empty() function to check whether this array is empty, simultaneously telling you whether there are errors and also which errors have occurred.
array with zero elements converts to false
http://php.net/manual/en/language.types.boolean.php
However, empty($error) still returns true, even though nothing is set.
That's not how empty() works. According to the manual, it will return true on an empty array only. Anything else wouldn't make sense.
From the PHP-documentation:
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 (0 as a float)
"0" (0 as a string)
NULL
FALSE
array() (an empty array)
var $var; (a variable declared, but without a value in a class)
function empty() does not work for testing empty arrays!
example:
$a=array("","");
if(empty($a)) echo "empty";
else echo "not empty"; //this case is true
a function is necessary:
function is_array_empty($a){
foreach($a as $elm)
if(!empty($elm)) return false;
return true;
}
ok, this is a very old question :) , but i found this thread searching for a solution and i didnt find a good one.
bye
(sorry for my english)
hi array is one object so it null type or blank
<?php
if($error!=null)
echo "array is blank or null or not array";
//OR
if(!empty($error))
echo "array is blank or null or not array";
//OR
if(is_array($error))
echo "array is blank or null or not array";
?>
I can't replicate that (php 5.3.6):
php > $error = array();
php > $error['something'] = false;
php > $error['somethingelse'] = false;
php > var_dump(empty($error));
bool(false)
php > $error = array();
php > var_dump(empty($error));
bool(true)
php >
exactly where are you doing the empty() call that returns true?
<?php
if(empty($myarray))
echo"true";
else
echo "false";
?>
In PHP, even if the individual items within an array or properties of an object are empty, the array or object will not evaluate to empty using the empty($subject) function. In other words, cobbling together a bunch of data that individually tests as "empty" creates a composite that is non-empty.
Use the following PHP function to determine if the items in an array or properties of an object are empty:
function functionallyEmpty($o)
{
if (empty($o)) return true;
else if (is_numeric($o)) return false;
else if (is_string($o)) return !strlen(trim($o));
else if (is_object($o)) return functionallyEmpty((array)$o);
// If it's an array!
foreach($o as $element)
if (functionallyEmpty($element)) continue;
else return false;
// all good.
return true;
}
Example Usage:
$subject = array('', '', '');
empty($subject); // returns false
functionallyEmpty($subject); // returns true
class $Subject {
a => '',
b => array()
}
$theSubject = new Subject();
empty($theSubject); // returns false
functionallyEmpty($theSubject); // returns true

Entering 0 into a field registers as empty?

Here is my code:
if (isset($_POST['addmonths'])){
if (!empty($_POST['months'])){
if (is_numeric($_POST['months'])){
$monthstoadd = $_POST['months'];
if ($monthstoadd < 1){
mysql_query("UPDATE users SET months='lifetime' WHERE username='$lookupuser'");
echo "Successfully set " . $lookupuser . " to lifetime";
}elseif ($monthstoadd > 0){
$monthstoadd = $monthstoadd*2592000;
mysql_query("UPDATE users SET months=months+'$monthstoadd' WHERE username='$lookupuser'");
echo "Successfully added " . $_POST['months'] . " months to " . $lookupuser . "'s paid time.";
}else{
echo "Error.";
}
}else{
echo "Months need to be numeric. If you're trying to set lifetime, use 0.";
}
}else{
echo "You didn't enter anything.";
}
}
When I enter 0, it should set the user to lifetime, but instead it just echos You didn't enter anything. Not really sure how to fix this. Any ideas?
Entering 0 into a field registers as empty?
Yes, it does. From the docs for empty:
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)
Any ideas?
empty doesn't seem like a good match for the condition you're checking for (did they type something in). Since you're already apparently using a marker field to indicate that there should be a value there, you might consider trim and a check against a blank string:
if (trim($_POST['months']) != ''){
Since you'r using $_POST['months] in four different places, I'd probably also cache the trimmed version to a local variable.
In general, You can substitute empty for isset (which returns false only of the variable doesn't exist or is null) or array_key_exists (for array keys).
In this case, you can do
if (!isset($_POST['months']) || $_POST['months'] === "")
Alternatively
if (!array_key_exists('months', $_POST) || $_POST['months'] === "")
Since this is POST data, null will never be a value (the browser can either not send the input or it sends an empty string, which PHP translates to ""). Therefore, isset and array_key_exists are interchangeable. isset is, however, preferred, since it's not a function and therefore is faster to run (not mention it's faster to write it).
You need to check the type to make sure it is empty instead of registers as empty with ===.
if ($_POST['months'] !== ''){
This checks to see if it exactly equivalent to empty. If it isn't it passes.

Categories