2

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"
);
3
  • possible duplicate of $var = $input || 'default' in PHP Commented Jul 5, 2013 at 22:28
  • @Barmar: Thanks for mentioning. I haven't thought that searching the (pseudo-)syntax would find me anything. Commented Jul 5, 2013 at 22:35
  • Took me a while, I found it with "php javascript default" Commented Jul 5, 2013 at 22:36

4 Answers 4

4

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.

Sign up to request clarification or add additional context in comments.

7 Comments

I forgot to try that! Thanks! But still this doesn't work in arrays, as I still get an error thrown. Thus +1 and I updated the question.
The full version is isset($var['property']) ? $var['property'] : 'default' - maybe try that?
@TomvanderWoerdt: If you have shorthands for retrieving such values, you can do eg. Arr::get($var, 'property') ?: 'default'. Not exactly the same, but may work in this specific case.
@TomvanderWoerdt: Or even better, if shorthands support that, it may simply be like Arr::get($var, 'property', 'default').
@Tom van der Woerdt: I would consider the comment as the answer, as I suppose there is no better way of doing it.
|
3

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.

2 Comments

This is a little bit more complicated than necessary, the idea with the setable default is nice however. I'll still would give the credit to Tom, as he was the first to mention ternary operators and thats what beasically every answer is revolving around and the other solutions (including the one offered by myself), are just a matter of what you need.
Sure, Hugo! I just think it's all a matter of personal taste. I like using functions / methods instead of inline code, because if I need to change the behavior of this in the future, I have just one place to deal with. It's the DRY principle. And please note the importance of the isset() use here: this is what prevents errors on trying to access non-existent keys on arrays.
1

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

1 Comment

@Jack: Exactly. The only difference is the order (ideone.com/9F0HZC), but it should not matter for most implementations.
0

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.

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.