0

What other alternatives for the if statement in the following code, are there?

$page_title = $titles['default'];
$page_desc  = $descriptions['default'];

if(array_key_exists($module, $titles) && !empty($titles[$module]))
{
    $page_title = $titles[$module];
}
if(array_key_exists($module, $descriptions) && !empty($descriptions[$module]))
{
    $page_desc  = $descriptions[$module];
}

The above code works great, I'm just looking to see if there's any room of improvement.

4

3 回答 3

4
$page_title = isset($titles[$module]) ? $titles[$module] : $titles['default'];
$page_desc  = isset($descriptions[$module]) ? $descriptions[$module] : $descriptions['default'];
于 2012-10-16T11:43:06.580 回答
2

What about this? ;)

($page_title = @$titles[$module]) or $page_title = $titles['default'];
($page_desc = @$descriptions[$module]) or $page_desc = $descriptions['default'];

or this?

$page_title = @$titles[$module] ?: $titles['default'];
$page_desc = @$descriptions[$module] ?: $descriptions['default'];
于 2012-10-16T11:54:16.720 回答
1

This is a slightly different way :) - I make no statement to say it is better... it depends on the situation.

$titles += array("$module" => $titles['default']);
$descriptions += array("$module" => $descriptions['default']);

$page_title = $titles[$module];
$page_desc = $descriptions[$module];
于 2012-10-16T11:55:26.127 回答