Jump to content

Detecting An Empty Array


phpQuestioner

Recommended Posts

How can I detect when an array has an empty value?

 

Here is what I have so far.

 

<?php

$products[] = "";

// This Works If The Above Array Does Not Exist At All
// But It Will Not Work; If The Above Array Is Present With An Empty Value
if (array_count_values($products) == 0)
{
$products[] = "Item Not Available";
}

foreach($products as $key => $value)
{
echo "$products<br>";
}

?>

 

I tried this; without an results:

 

<?php

$products[] = "";

// This Works If The Above Array Does Not Exist At All
// But It Will Not Work; If The Above Array Is Present With An Empty Value
if (array_count_values($products) == 0)
{
$products[] = "Item Not Available";
}
else if ($products == NULL) 
{
$products[] = "Item Not Available";
}

foreach($products as $key => $value)
{
echo "$products<br>";
}

?>

Link to comment
https://forums.phpfreaks.com/topic/75073-detecting-an-empty-array/
Share on other sites

<?php

$products[] = "";

// This Works If The Above Array Does Not Exist At All
// But It Will Not Work; If The Above Array Is Present With An Empty Value
if (!$products)
{
$products[] = "Item Not Available";
}

foreach($products as $key => $value)
{
echo "$products<br>";
}

?>

 

like that? Sorry, I don't use arrays if I don't have to.

Hi,

 

The problem is that you're initializing the array with a value, then checking whether there are any values in the array, which will return true or 1 or whatever. What you can do instead is initialize $products to an empty array, and I used the count function instead of array_count_values:

 

<?php

$products = array();

// This Works If The Above Array Does Not Exist At All
// But It Will Not Work; If The Above Array Is Present With An Empty Value
if (count($products) == 0)
{
$products[] = "Item Not Available";
}

foreach($products as $key => $value)
{
echo "$value<br>";
}

?>

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.