I have an array called tagcat , like so
$tagcat = array();
....
while ( $stmt->fetch() ) {
$tagcat[$tagid] = array('tagname'=>$tagname, 'taghref'=>$taghref);
}
Using print_r($tagcat) i get the following result set
Array ( [] => Array ( [tagname] => [taghref] => ) )
Using var_dump($tagcat), i get
array(1) { [""]=> array(2) { ["tagname"]=> NULL ["taghref"]=> NULL } }
In php, i want to check if the array is empty. But when using the following conditions, it always finds something in the array, which is not true!
if ( isset($tagcat) ) {
echo 'array is NOT empty';
} else {
echo 'EMPTY!!!';
}
if ( !empty($tagcat) ) {
echo 'array is NOT empty';
} else {
echo 'EMPTY!!!';
}
How do i check if the array is empty?
Use array_filter
if(!array_filter($array)) {
echo "Array is empty";
}
This was to check for the single array. For multi-dimensional array in your case. I think this should work:
$empty = 0;
foreach ($array as $val) {
if(!array_filter($val)) {
$empty = 1;
}
}
if ($empty) {
echo "Array is Empty";
}
If no callback is supplied, all entries of $array equal to FALSE will be removed.
With this it only returns the value which are not empty. See more in the docs example Example #2 array_filter() without callback
If you need to check if there are ANY elements in the array
if (!empty($tagcat) ) { //its $tagcat, not tagcat
echo 'array is NOT empty';
} else {
echo 'EMPTY!!!';
}
Also, if you need to empty the values before checking
foreach ($tagcat as $cat => $value) {
if (empty($value)) {
unset($tagcat[$cat]);
}
}
if (empty($tagcat)) {
//empty array
}
Hope it helps
EDIT: I see that you have edited your $tagcat var. So, validate with vardump($tagcat) your result.
if (empty($array)) {
// array is empty.
}
if you want remove empty elements try this:
foreach ($array as $key => $value) {
if (empty($value)) {
unset($array[$key]);
}
}
Related
I need a help. I have two arrays. I need to check if the values in first array are present in second or not. The arrays are as:
$maindata=array(array('id'=>3),array('id'=>7),array('id'=>9));
$childata=array(array('id'=>7),array('id'=>11),array('id'=>3),array('id'=>123));
Here, I need to check if each value from first array is present inside second array or not. If yes, then should return true else false at each time.
Here you go, you can use the in_array() for PHP.
$maindata=array( array('id'=>3),array('id'=>7),array('id'=>9) );
$childata=array( array('id'=>7),array('id'=>11),array('id'=>3),array('id'=>123) );
foreach( $maindata as $key => $value )
{
if( in_array( $value, $childata ) )
{
echo true;
}
else
{
echo false;
}
}
You could also remove the whole if else and replace with a single line.
echo ( in_array( $value, $childata ) ? true : false );
Reference -
http://php.net/manual/en/function.in-array.php
https://code.tutsplus.com/tutorials/the-ternary-operator-in-php--cms-24010
To check if an array contains a value:
if (in_array($value, $array)) {
// ... logic here
}
To check if an array contains a certain key:
if (array_key_exists($key, $array)) {
// ... logic here
}
Resources
in_array - PHP Manual
array_key_exists() - PHP Manual
Following code will return true only if all elements of main array exists in second array, false otherwise:
$maindata=array(array('id'=>3),array('id'=>7),array('id'=>9));
$childata=array(array('id'=>3),array('id'=>7),array('id'=>11),array('id'=>123));
$match = 0;
foreach( $maindata as $key => $value ) {
if( in_array( $value, $childata ) ) {
$match++;
}
}
if($match == count($maindata)){
// return true;
} else {
// return false;
}
Use array_intersect
if(!empty(array_intersect($childata, $maindata)))
{
//do something
}
or
$result = count(array_intersect($childata, $maindata)) == count($childata);
Use array_column and array_intersect.
$first = array_column($maindata, 'id');
$second = array_column($childata, 'id');
//If intersect done, means column are common
if (count(array_intersect($first, $second)) > 0) {
echo "Value present from maindata in childata array.";
}
else {
echo "No values are common.";
}
No doubt it has been discussed few million times here and yes once again I am posting something related with it.
I have the following code.
$address = "#&#&#&";
$addr = explode("#&",$address);
it returns
Array
(
[0] =>
[1] =>
[2] =>
[3] =>
)
Now the values are empty.So I am doing a check.
If(!empty($addr))
{
echo 'If print then something wrong';
}
And it still prints that line.Not frustrated yet but will be soon
Run array_filter() to remove empty entries, then check if the array itself is empty()
if (empty(array_filter($addr)))
Note that array_filter() without a callback will remove any "falsey" entries, including 0
To check if the array contains no values you could loop the array and unset the no values and then check if the array is empty like the following.
$addresses = "#&#&#&";
$addresses = explode("#&", $addresses);
foreach ( $addresses as $key => $val ) {
if ( empty($val) ) {
unset($addresses[$key]);
}
}
if ( empty($addresses) ) {
echo 'there are no addresses';
}
else {
// do something
}
This is not an empty array, empty array has no elements, your have four elements, each being an empty string, this is why empty is returning false.
You have to iterate over elements and test whether they are all empty, like
$empty=True;
foreach ($addr as $el){
if ($el){
$empty=False;
break;
}
}
if (!$empty) echo "Has values"; else echo "Empty";
You are checking if the array contains elements in it. What you want to do is check if the elements in the array are empty strings.
foreach ($addr as $item) {
if (empty($item)) {
echo 'Empty string.';
} else {
echo 'Value is: '.item;
}
}
The array is not empty, it has 4 items. Here's a possible solution:
$hasValues = false;
foreach($addr as $v){
if($v){
$hasValues = true;
break;
}
}
if(!$hasValues){
echo 'no values';
}
I have the following query:
//product density
$stmt_density = $conn->prepare("SELECT density FROM product_density
WHERE product_id = :productid ");
$stmt_density->execute(array(':productid' => "$pid"));
$density = $stmt_density->fetchAll();
If density is not present the value will be "NULL".
var_dump($density);
gives following output:
array(1) { [0]=> array(2) { ["density"]=> NULL [0]=> NULL } }
I need to check whether the array is having values or not and to provide select options, if array not empty.
Depending on whether you expect to get back multiple results from your query could change the answer, especially if you get back say 1 result with a NULL and one without. But you could do...
function validResult($density) {
foreach($density as $item) {
if($item["density"] == NULL) return false;
}
return true;
}
if(validResult($density))
echo "We have values";
else
echo "Array contains null";
The function will return false if any result has null, regardless of how many are not null
Try something like this
function check($array, $key)
{
if(array_key_exists($key, $array)) {
if (is_null($array[$key])) {
echo $key . ' is null';
} else {
echo $key . ' is set';
}
}
}
I think you are trying to check for null values in an array try
function array_key_exists_r($needle, $haystack)
{
foreach ($haystack as $v) {
foreach ($v as $k=>$v1) {
if(empty($v1) || $v1 ==$needle)
$result[$k] = $v1;
}
if ($result) return $result;
}
}
$r = array_key_exists_r('NULL', $density);
print_r($r); //Array ( [density] => [0] => )
Function will give you all empty or NULL keys as an array
I have a form posting a multidimensional array to my PHP script, I need to know if all the values in the array are empty or not.
Here is my array:
$array[] = array('a'=>'',
'b'=>array('x'=>''),
'c'=>array('y'=>array('1'=>'')),
'd'=>'');
I tried using array_reduce(), but it's just returning an array:
echo array_reduce($array, "em");
function em($a,$b){
return $a.$b;
}
Any ideas?
I noticed this has been hanging around for a while, this is a custom function that works quite well.
function emptyArray($array) {
$empty = TRUE;
if (is_array($array)) {
foreach ($array as $value) {
if (!emptyArray($value)) {
$empty = FALSE;
}
}
}
elseif (!empty($array)) {
$empty = FALSE;
}
return $empty;
}
if all items in the array is empty then the function will return true, but if one item in the array is not empty then the function will return false.
Usage:
if (emptyArray($ARRAYNAME)) {
echo 'This array is empty';
}
else {
echo 'This array is not empty';
}
How can I check an array recursively for empty content like this example:
Array
(
[product_data] => Array
(
[0] => Array
(
[title] =>
[description] =>
[price] =>
)
)
[product_data] => Array
(
[1] => Array
(
[title] =>
[description] =>
[price] =>
)
)
)
The array is not empty but there is no content. How can I check this with a simple function?
Thank!!
function is_array_empty($InputVariable)
{
$Result = true;
if (is_array($InputVariable) && count($InputVariable) > 0)
{
foreach ($InputVariable as $Value)
{
$Result = $Result && is_array_empty($Value);
}
}
else
{
$Result = empty($InputVariable);
}
return $Result;
}
If your array is only one level deep you can also do:
if (strlen(implode('', $array)) == 0)
Works in most cases :)
Solution with array_walk_recursive:
function empty_recursive($value)
{
if (is_array($value)) {
$empty = TRUE;
array_walk_recursive($value, function($item) use (&$empty) {
$empty = $empty && empty($item);
});
} else {
$empty = empty($value);
}
return $empty;
}
Assuming the array will always contain the same type of data:
function TestNotEmpty($arr) {
foreach($arr as $item)
if(isset($item->title) || isset($item->descrtiption || isset($item->price))
return true;
return false;
}
Short circuiting included.
function hasValues($input, $deepCheck = true) {
foreach($input as $value) {
if(is_array($value) && $deepCheck) {
if($this->hasValues($value, $deepCheck))
return true;
}
elseif(!empty($value) && !is_array($value))
return true;
}
return false;
}
Here's my version. Once it finds a non-empty string in an array, it stops. Plus it properly checks on empty strings, so that a 0 (zero) is not considered an empty string (which would be if you used empty() function). By the way even using this function just for strings has proven invaluable over the years.
function isEmpty($stringOrArray) {
if(is_array($stringOrArray)) {
foreach($stringOrArray as $value) {
if(!isEmpty($value)) {
return false;
}
}
return true;
}
return !strlen($stringOrArray); // this properly checks on empty string ('')
}
If anyone stumbles on this question and needs to check if the entire array is NULL, meaning that each pair in the array is equal to null, this is a handy function. You could very easily modify it to return true if any variable returns NULL as well. I needed this for a certain web form where it updated users data and it was possible for it to come through completely blank, therefor not needing to do any SQL.
$test_ary = array("1"=>NULL, "2"=>NULL, "3"=>NULL);
function array_empty($ary, $full_null=false){
$null_count = 0;
$ary_count = count($ary);
foreach($ary as $value){
if($value == NULL){
$null_count++;
}
}
if($full_null == true){
if($null_count == $ary_count){
return true;
}else{
return false;
}
}else{
if($null_count > 0){
return true;
}else{
return false;
}
}
}
$test = array_empty($test_ary, $full_null=true);
echo $test;
$arr=array_unique(array_values($args));
if(empty($arr[0]) && count($arr)==1){
echo "empty array";
}
Returns TRUE if passed a variable other than an array, or if any of the nested arrays contains a value (including falsy values!). Returns FALSE otherwise.
Short circuits.
function has_values($var) {
if (is_array($var)) {
if (empty($var)) return FALSE;
foreach ($var as $val) {
if(has_values($val)) return TRUE;
}
return FALSE;
}
return TRUE;
}
Here's a good utility function that will return true (1) if the array is empty, or false (0) if not:
function is_array_empty( $mixed ) {
if ( is_array($mixed) ) {
foreach ($mixed as $value) {
if ( ! is_array_empty($value) ) {
return false;
}
}
} elseif ( ! empty($mixed) ) {
return false;
}
return true;
}
For example, given a multidimensional array:
$products = array(
'product_data' => array(
0 => array(
'title' => '',
'description' => null,
'price' => '',
),
),
);
You'll get a true value returned from is_array_empty(), since there are no values set:
var_dump( is_array_empty($products) );
View this code interactively at: http://codepad.org/l2C0Efab
I needed a function to filter an array recursively for non empty values.
Here is my recursive function:
function filterArray(array $array, bool $keepNonArrayValues = false): array {
$result = [];
foreach ($array as $key => $value) {
if (is_array($value)) {
$value = $this->filterArray($value, $keepNonArrayValues);
}
// keep non empty values anyway
// otherwise only if it is not an array and flag $keepNonArrayValues is TRUE
if (!empty($value) || (!is_array($value) && $keepNonArrayValues)) {
$result[$key] = $value;
}
}
return array_slice($result, 0)
}
With parameter $keepNonArrayValues you can decide if values such 0 (number zero), '' (empty string) or false (bool FALSE) shout be kept in the array. In other words: if $keepNonArrayValues = true only empty arrays will be removed from target array.
array_slice($result, 0) has the effect that numeric indices will be rearranged (0..length-1).
Additionally, after filtering the array by this function it can be tested with empty($filterredArray).