1

I want avoid several ifs and my question is:

Is there a function or a way to add several arrays ($a, $b) to an array, but only if an array ($a, $b) is not empty?

Given:

$a = ['foo' => 'bar'];
$b = [];

My code:

$c = [];

if (count($a))
{
  $c['a'] = $a;
}

if (count($b))
{
  $c['b'] = $b;
}

Yes, I need string keys with a specific name.

2
  • Yes, make a function and don't repeat yourself. Commented Aug 19, 2014 at 14:36
  • This looks more like a coding style question to me. If you post a real code fragment you have problems with, you'll get better answers. Commented Aug 19, 2014 at 14:42

4 Answers 4

5

If all of your elements are arrays then you can easily cast out the empty ones with array_filter. For example, taking advantage of the fact that your keys are equal to variable names you can simply do

$c = array_filter(compact('a', 'b'));
Sign up to request clarification or add additional context in comments.

Comments

3

Well, how about

$c = array_filter(compact('a', 'b'));

Just kidding. I don't really recommend this. "Smart(ass)" code sucks, especially in php. Be verbose, be readable.

(Looks like the OP didn't get the joke. Too bad...)

1 Comment

@Jon: it depends, I guess. I asked the OP to give us a real-life example, because foobar codez don't really make sense here.
1

You can do the following:

$c = array();

function addToC(){
   foreach(func_get_args() as $arg){
    if(is_array($arg) && !empty($arg){
     $c[] = $arg; 
    }
   }
}

Comments

0

It's horribly hacky, and just covering up for bad design, but there are variable variables:

$to_do = array('a', 'b');
foreach ($to_do as $key) {
   if (count($$key)) {
     $c[$key] = $$key;
   }
}

Note the doubled $. e.g.

php > echo $bar;
PHP Notice:  Undefined variable: bar in php shell code on line 1
php > $foo = 'bar';
php > $$foo = 'baz';
php > echo $bar;
baz

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.