Is this the correct way of checking empty array? - php

I want to check if array is empty or not, i wrote few lines of code for it
if(array() == $myArray){
echo "Array";
}
or
if(array() === $myArray){
echo "Array";
}
I'm confused which one to use, as the second condition also checks type. But i think in the case of array we don't need to check their type.
Please anybody can suggest me which one to use.

you can check it by using empty() function like below
<?php
if(empty($myArray)) {
//condition
}
?>

if (! count($myArray)) {
// array is empty
}
Let php do its thing and check for booleans.

Use empty:
if (empty($myArray)) {
...
}

Try this :
<?php
$array = array();
if(empty($array))
{
echo "empty";
} else
{
echo "some thing!";
}
?>

It's always better to check first whether it is array or not and then it is empty or not. I always use like this because whenever I check only empty condition somewhere I don't get the expected result
if( is_array($myArray) and !empty($myArray) ){
.....
.....
}

<?php
if(empty($yourarry)){
}
OR
if(isset($yourarry)){
}
OR
if(count($yourarry)==0){
}

It depends:
Use count==0 if your array could also be an object implementing Countable
Use empty otherwise
array() == $myArray is unreadable, you should avoid it. You can see the difference between count and empty here.

Related

How to check if $row['column_name'] is returning empty php mysql

I have a table with columns
id,name,phone,describe
While fetching the values from this table i am using
$row=mysql_fetch_array($query)
Now i want to check whether
$row['describe']
is returning empty value. How to check in php??
You can use ==0, this will check if it equals to 0:
if ($row['describe']==0) { /* code to do */ }
Or empty(), this will check if it is empty:
if (empty($row['describe'])) { /* code to do */ }
Personally, I would prefer !empty() as this will check if the variable is empty.
Hope this helps, thanks!
Try this :
if(empty($row['describe'])) {
//$row['describe'] is empty
} else {
//$row['describe'] is not empty
}
Also please dont use mysql_*. It's deprecated and removed from PHP 7. Use mysqli_* or PDO.
Use if condition like below
if ($row['describe'] == ""){
echo "Description is empty";
}else{
echo $row['describe'];
}
This can help you. First check the query doesn't return empty then check the describe column is not empty. Only then go for performing action(s).
if ((mysql_num_rows($result) !=0 ) && (!empty($row['describe']) )
{ //PERFORM ACTION }

PHP take string and check if that string exists as a variable

I have an interesting situation. I am using a form that is included on multiple pages (for simplicity and to reduce duplication) and this form in some areas is populated with values from a DB. However, not all of these values will always be present. For instance, I could be doing something to the effect of:
<?php echo set_value('first_name', $first_name); ?>
and this would work fine where the values exist, but $user is not always set, since they may be typing their name in for the first time. Yes you can do isset($first_name) && $first_name inside an if statement (shorthand or regular)
I am trying to write a helper function to check if a variable isset and if it's not null. I would ideally like to do something like varIsset('first_name'), where first_name is an actual variable name $first_name and the function would take in the string, turn it into the intended variable $first_name and check if it's set and not null. If it passes the requirements, then return that variables value (in this case 'test'). If it doesn't pass the requirements, meaining it's not set or is null, then the function would return '{blank}'.
I am using CodeIgniter if that helps, will be switching to Laravel in the somewhat near future. Any help is appreciated. Here is what I've put together so far, but to no avail.
function varIsset($var = '')
{
foreach (get_defined_vars() as $val) {
if ($val == $var) {
if (isset($val) && $val) {
echo $val;
}
break;
}
}
die;
}
Here is an example usage:
<?php
if (varIsset('user_id') == 100) {
// do something
}
?>
I would use arrays and check for array keys myself (or initialize all my variables...), but for your function you could use something like:
function varIsset($var)
{
global $$var;
return isset($$var) && !empty($$var);
}
Check out the manual on variable variables. You need to use global $$var; to get around the scope problem, so it's a bit of a nasty solution. See a working example here.
Edit: If you need the value returned, you could do something like:
function valueVar($var)
{
global $$var;
return (isset($$var) && !empty($$var)) ? $$var : NULL;
}
But to be honest, using variables like that when they might or might not exist seems a bit wrong to me.
It would be a better approach to introduce a context in which you want to search, e.g.:
function varIsset($name, array $context)
{
return !empty($context[$name]);
}
The context is then populated with your database results before rendering takes place. Btw, empty() has a small caveat with the string value "0"; in those cases it might be a better approach to use this logic:
return isset($context[$name]) && strlen($name);
Try:
<?php
function varIsset($string){
global $$string;
return empty($$string) ? 0 : 1;
}
$what = 'good';
echo 'what:'.varIsset('what').'; now:'.varIsset('now');
?>

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 if $var = anything in an array?

I need to be able to test if $post_count is equal to any number in a given array. Here is an example of what I am trying to achieve:
$posts_even = array(2,4,6,8,10);
$posts_odd = array(1,3,5,7,9);
$posts_ev3 = array(1,4,7,10);
$posts_ev4 = array(1,5,9);
--
$post_count=1;
$post_count=++; //in wordpress loop so each subsequent post is +1
--
if ($post_count= //any value in $posts_ev4) :
echo 'this'
else :
NULL;
endif;
I have been able to make this work using the or operator but I end up with very long blocks of code.....
if (($post_count=1) || ($post_count=2)) :
echo 'this'
else :
NULL;
endif;
I am guessing there is a simpler way to do this but I am new to PHP so I am not sure! Any help would be greatly appreciated.
Try:
if (in_array($post_count, $post_ev4)) {}
See: in_array()
Use in_array() to check if value exists in array.
if (in_array($post_count, $posts_ev4)) :
echo 'this'
else :
NULL;
endif;
Check out the isset() function in the PHP Manual.
There are array functions in php. Ypu can use "is_array" function to check whether its array or not. & to check for a value you can use "in_array" function.
if(is_array($array) && in_array($post_count,$array))
{
// do operation
}

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