问题描述:

I'm curious is there a way to write a shorthand setter in PHP. My primary quest when writing code is to make it as tight as possible and I think the following is kind of cumbersome:

$value = "Which array do I go in?";

if(true)

$arr_1[] = $value;

else

$arr_2[] = $value;

Is there a better way to write that? I tried to use the shorthand if:

(true)?$arr_1[]:$arr_2[] = "Which array do I go in?";

But that doesn't seem to work. Anyone have any cool tricks for this type of situation?

Thanks!

网友答案:

Another option (e.g. if you can't/don't want to use globals).

${$cond?'arr_1':'arr_2'}[] = $value;
网友答案:

There is no shorthand for what you are trying to do. Also you should realize that making code "as tight as possible" often comes at the cost of readability.

EDIT: There is some ugly hacks to do what you want, but I would strongly recommend against. E.g.:

$GLOBALS[cond ? 'varname1' : 'varname2'] = $value;
网友答案:

Another hack would be:

$arr = ($cond ? &$arr_1 : &$arr_2);
$arr[] = 'Which array do I go in';

it's two lines but it doesn't require global and would work in a function. However for readability it is probably better to use an if statement. (Note: the & is making a reference to the variable, which is why this works). Another (which might make you understand HOW the ternary operator works) would be:

$cond ? $arr_1[] = $value : $arr_2[] = $value;

You see the ternary operator only evaluates (runs the code path) of the successful evaluation (on the right side of the ? if true, on the right side of : if false). However if you think this is faster than using 'if' you are wrong, your less 'tight' code will actually perform better.

相关阅读:
Top