Henrik Petterson
Henrik Petterson

Reputation: 7104

Conditions within an array in PHP

I have a great couple of variables named $value1, $value2 etc. I want to create an array key for each variable only if the variable is not empty. Something like this:

$array = array(
    If (!empty($value1)) { "bar" => "foo", }
    If (!empty($value2)) { "foo" => "bar", }
);

How do I do this and what would be good practice?

Upvotes: 0

Views: 83

Answers (3)

Davide Pastore
Davide Pastore

Reputation: 8738

You can use Variable variables:

$array = array();
$count = 4; //You can have n variables
for($i = 1; $i <= $count; $i++){
    if(isset(${'value' . $i})){
      $array[$i] = ${'value' . $i};
    }
}

Upvotes: -2

NDM
NDM

Reputation: 6840

PHP arrays are dynamic, so you can add stuff to it easily:

$array = array(); // start with empty one

if (!empty($value1)) $array['bar'] = 'foo';
if (!empty($value2)) $array['foo'] = 'bar';

// you don't even have to specify a key, 
// it will just increment accordingly if left out
if (!empty($value3)) $array[] = 'foobar';

this will result in (if all 3 vars are non-empty):

array(3) {
  'a' => 'foo',
  'b' => 'bar',
  0   => 'foobar'
}

http://php.net/manual/en/language.types.array.php#language.types.array.syntax.modifying

Upvotes: 3

Marc B
Marc B

Reputation: 360762

You can't do it that way - if you use the array shortcut notation, you WILL create an entry in the array, whether there's a value or not. You'll have to test/set each key individually:

$arr = array();
if (!empty($value)) { $arr['bar'] = 'foo' }

Upvotes: 3

Related Questions