hugo der hungrige
hugo der hungrige

Reputation: 12912

Set simple defaults when declaring PHP-arrays

In JavaScript I can do the following:

var variable = {
  variable: arg || "bla";
}
// variable.variable = "bla" if arg is false, null or unefined
var variable [
   arg || "bla
]
// variable[0] = "bla" if arg is false, null or unefined

If arg isn't defined, the value gets "bla". Pretty neat. I love this!

Is there something similiar possible in php? I can do an if with an isset(), but that produces a lot of code, especially if I have an array like this for example:

$postData = array(
    'birthday' => $aData['oBirthday'] /* ????? */,
    'country' => $aData['sCountry'],
    'first_name' => $aData['sFirstName'],
    'last_name' => $aData['sLastName']
);

EDIT:

The shortest syntax possible I found so far (Thanks to Tom!):

$postData = array(
'birthday' => isset($aData['oBirthday']) ? $aData['oBirthday'] : "aaaaaaaa"
);

Upvotes: 2

Views: 84

Answers (4)

Lebugg
Lebugg

Reputation: 313

I know this ugly, but you can do the following:

@ $var = $arr['key'] ?: DEFAULT_VALUE;

I sometimes use it because even though this is bad, I know what it does, so I allow myself to use it.

Upvotes: 0

Tadeck
Tadeck

Reputation: 137320

For single parameters use ternary operators, possibly in the form proposed by Tom in his answer.

For arrays of parameters you can use array_merge():

$defaults = array(
    'birthday' => '1980-03-04',
    'country' => 'United States',
    'first_name' => 'John',
    'last_name' => 'Smith',
);

$params = array(
    'first_name' => 'Jane',
    'last_name' => 'Johnson',
);

$results = array_merge($defaults, $params); // uses $defaults as base

Proof is here: http://ideone.com/0CewM1

Upvotes: 1

Marcovecchio
Marcovecchio

Reputation: 1332

I have faced the same problem years ago, and my solution is a simple function:

function GetArrayData(array $array, $key, $default = NULL)
{
  return isset($array[$key]) ? $array[$key] : $default;
}

Not too elegant, but safe as hell. Use $_GET or $_POST as the array, and you also have a great way to read form or query string data. I use a similar approach to get session values also.

Upvotes: 3

Tom van der Woerdt
Tom van der Woerdt

Reputation: 29975

Yeah, PHP has the ?: operator that does the same.

$var = arg ?: "bla";

This is a ternary operator, usually written as condition ? if_true : if_false but :

Since PHP 5.3, it is possible to leave out the middle part of the ternary operator. Expression expr1 ?: expr3 returns expr1 if expr1 evaluates to TRUE, and expr3 otherwise.

Upvotes: 4

Related Questions