How can I determine whether the values in a multi-dimensional array are empty?

Source: Internet
Author: User
How can I determine whether the values in a multi-dimensional array are empty? For example, two arrays $ arr are considered null, and $ brr is considered to have a value.
$arr=array(0=>'', 1=>array(0=>'' ,1=>array(0=>'') ));$brr=array(0=>'', 1=>array(0=>'' ,1=>array(0=>'1') ));


Reply to discussion (solution)

Yes.

$arr = array(0=>'', 1=>array(0=>'' ,1=>array(0=>'') ));var_dump(preg_replace('/[",\[\]]/', '', json_encode($arr)));
String (0 )""
Obviously, $ brr will be string (1) "1"

Yes.

$arr = array(0=>'', 1=>array(0=>'' ,1=>array(0=>'') ));var_dump(preg_replace('/[",\[\]]/', '', json_encode($arr)));
String (0 )""
Obviously, $ brr will be string (1) "1"


In this way, if the array is large, it will affect the efficiency? Or can we recursively determine whether there is a value?

It may be better.

$arr = array(0=>'', 1=>array('a'=>'' ,1=>array(0=>'') ));var_dump(preg_replace('/"\w+":|[",{}\[\]]/', '', json_encode($arr)));

That's strange. I only executed two functions.
It must be much faster than recursion.

Recursive writing

$arr = array(0=>'', 1=>array('a'=>'' ,1=>array(0=>'') ));var_dump(foo($arr));function foo($ar) {  if(empty($ar)) return true;  if(is_array($ar)) {    foreach($ar as $v) {      if(! foo($v)) return  false;    }    return true;  }  return flase;}

Recursive writing

$arr = array(0=>'', 1=>array('a'=>'' ,1=>array(0=>'') ));var_dump(foo($arr));function foo($ar) {  if(empty($ar)) return true;  if(is_array($ar)) {    foreach($ar as $v) {      if(! foo($v)) return  false;    }  }  return flase;}


Thank you !!

$arr=array(0=>'',1=>array(0=>'',1=>array(0=>'')));$brr=array(0=>'',1=>array(0=>'',1=>array(0=>'1')));echo test($arr).'
';echo test($brr);function test(&$array){static $r = 0;if(!is_array($array)){if(empty($array)){$r=0;}else{$r=1;}}foreach ($array as $key => $value) {if (is_array($value)) {test($array[$key]);} else {if(empty($value)){$r=0;}else{$r=1;}}}return $r;}

Result:
0
1

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.