Jump to content

Recommended Posts

Hey all,

I'm looking for a quick, boolean-style method of checking for empty values in an array without looping through it first. Is there something like:

$newarray = array('first' => "", 'second' => 2);
if (empty_value($newarray)) {
   return false;
}

 

I made up the "empty_value()" thing. But essentially I'd like to check for empty values before deciding to loop through the array.

 

Any ideas?

 

Mark

Link to comment
https://forums.phpfreaks.com/topic/50844-checking-for-empty-values-in-array/
Share on other sites

There is no way to tell if any 1 element of an array is empty in constant time (O(1)).  The best you can do is O(n) where n is the length of the array.  You can of course define a function that traverses the array and returns true as soon as it finds a null value.

 

<?php
$newarray = array('first' => "", 'second' => 2);
if (empty_value($newarray)) {
   return false;
}

function empty_value($arr)
{
  foreach($arr as $val){
   if ($val === null)
     return true;
  }
  return false;
}
?>

 

Best,

 

Patrick

Hmm,

 

Your first "return false" is invalid, not in a function.

 

And empty string is not a null value

 

try

<?php
$newarray = array('first' => "", 'second' => 2);
if (empty_value($newarray)) {
   echo "Empty value found";
}

function empty_value($arr)
{
  foreach($arr as $val){
   if (!$val)
     return true;
  }
  return false;
}
?>

Your first "return false" is invalid, not in a function.

 

D'oh.  Just copied and pasted from above.

 

And empty string is not a null value

 

You're right... I used === null because of a case like this:

 

<?php
array("foo" => false, "bar" => 0, "baz" => "");
// These would all return true in "if(!$val)", probably not the expected result (thanks PHP!).
?>

 

Maybe we should have done something like this:

 

<?php
$newarray = array('first' => "", 'second' => 2);
if (empty_value($newarray)) {
   echo "Empty value found";
}

function empty_value($arr)
{
  foreach($arr as $val){
   if ($val === "" || $val === null)
     return true;
  }
  return false;
}
?>

 

Patrick

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.