PHP递归函数,返回错误

I create a PHP function to test if $var exist and is not empty.

But, But I have a problem that I can't identify :

  • In my foreach, return false is ignored because another 'return' return first.

LOOK :

    function notEmpty($var, $r=false){
    if(gettype($var)=='string' OR gettype($var)=='integer'){
        if($r==false){
            if(isset($var) AND @!empty($var)){
                return true;
            }else{return false;}
        }else{
            if(!isset($var) AND @empty($var)){
                return false;
            }
        }
    }elseif(gettype($var)=='array'){
        foreach($var as $val){
            if(gettype($val)=='array'){
                notEmpty($val, true);
            }else{
                if(empty($val) OR $val==''){echo "string";
                    return false;
                }
            }
        }
        return true;
    }else{return null;}
}

I call my function like : - notEmpty(array($val1, $val2, $val3));

I guess this is more or less what you are looking for:

<?php

function notEmpty($array, $recursive=false) {
    $empty = array_filter($array, function($element) use ($recursive) {
        if (is_array($element) && $recursive) {
            return !notEmpty($element);
        } else {
            return empty($element);
        }
    });
    return 0===count($empty);
}

var_dump(notEmpty([1, 2, 3]));
var_dump(notEmpty(['foo', '', 'bar']));
var_dump(notEmpty(['foo', null, 'bar']));
var_dump(notEmpty(['foo', [1,2,3], 'bar']));
var_dump(notEmpty(['foo', [1,null,3], 'bar']));
var_dump(notEmpty(['foo', [1,null,3], 'bar'], true));

The output of that is:

bool(true)
bool(false)
bool(false)
bool(true)
bool(true)
bool(false)