Jump to content

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>";
}

?>

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • 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.