1

I can't find out how to check if an array is empty. I know empty() means 100% empty, including keys. But my array looks like this when there are (in this case) no products:

Array
(
    [0] => 
)

How can I check if an array is empty like that? Preferably only for this exact "array list" because on a page that does have products I also have [0] => as first value, which I filter out (but this is after I need to check for the empty array).

Edit:

if(empty(array_values($relatedcr))){
    echo 'empty';
}else{
    echo 'not empty';
}

4 Answers 4

3

get the value as array, then check it.

empty(array_values($array));

Here is a test code:

<?php 
$array=[1];
unset($array[0]);
var_dump($array);
var_dump(empty($array));
var_dump(['']);
var_dump(empty(['']));

output: demo here

array(0) {
}
bool(true)
array(1) {
  [0]=>
  string(0) ""
}
bool(false)
Sign up to request clarification or add additional context in comments.

3 Comments

I added the code like in my edited post. But I get not empty on a page with products and a page without products. When I print the array I still get the same result as in my original post.
@twan empty string have difference with empty value.
You lost me at the test code. Thanks anyway you pointed me in the right direction, got it to work with array_filter.
0

This way:

foreach ($playerlist as $key => $value) {
        if (empty($value)) { //checking if array value are empty
           unset($playerlist[$key]);
        }
    }

Comments

0
<?php
$user= [
    "name"=> "",
    "age" => ""
];
$data = array_filter($user);
echo (empty($data)) ? "empty" : "not empty";

output : empty

Comments

0

You can do it using array_filter then check for empty

  $b = array_filter($array1);

    if (empty($b))
    {
        echo "empty";
    }
    else
    {
        echo "not empty";
    }

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.