简体   繁体   中英

Even if array for foreach is empty, run it

I've came across a little problem. Well I'm getting from wordpress database some user_meta data, which is stored as array, by declaring variable $all_meta_for_user = get_user_meta($user_id, 'meta_key', false) . Then, I'd like to check if some specific data is present, and if so, do something, if not, do something else. I've got somewhere here at stackoverflow a hint, that I can achieve it in that way:

foreach($all_meta_for_user as $key=>$val) :
        if (array_key_exists ('some_key', $val) && array_key_exists ('some_other', $val)) { do something } else {do something else } 
endforeach;

And that works good, as long as associated 'meta_key' is present in database (which is obvious :)). But what, if it's not? Then, again obviously, foreach is false and it doesn't run. Basically, I'd like to show content after else even if the array is empty. How I can alter my code, to achieve that? I think I could get it working, if I first check if array is empty, if no - do code with foreach, if yes - do my else. But the problem is, in my else there's a lot of code, so I'd like to avoid duplicating it.

So, simply, the question is, how to make that in a nice way, that will not double my code :) Thanks!

PS I really couldn't find appropriate topic name. If someone have a better idea how to name it, please leave a comment so I can change it! Thanks!

You can create your "else" function, and combine that with the if/else idea. That way you won't have any repetition, just function calls:

function elseFunction() {
    //do something else
}

if (!empty($all_meta_for_user)) {
    foreach($all_meta_for_user as $key=>$val){
        if (array_key_exists ('some_key', $val) && array_key_exists ('some_other',$val)){ 
            // do something  
        }
        else { 
            elseFunction(); // this is changed
        }
    }
}
else {
    elseFunction();
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM