I have feeling that the following code can be shortened but have no idea how to rewrite it :)
$post_type = isset( $_GET['post_type'] ) ? $_GET['post_type'] : '';
if( $post_type == 'faq' && !isset( $_REQUEST['mode'] ) )
$_REQUEST['mode'] = 'excerpt';
// if I just go with else... it doesn't work
elseif( $post_type !== 'faq' && !isset( $_REQUEST['mode'] ) )
$_REQUEST['mode'] = 'list';
Update
As you can see, !isset( $_REQUEST['mode'] )
is used twice. $post_type == 'faq'
is also used twice, but in the elseif I'm checking negative.
Seriously there is no way to rewrite it to one if
without else
...?
How about using a ternary operator for testing 'faq' ?
$post_type = isset( $_GET['post_type'] ) ? $_GET['post_type'] : '';
if (!isset( $_REQUEST['mode'] )) {
$_REQUEST['mode'] = ($post_type == 'faq') ? 'excerpt' : 'list';
}
maybe use more intermediate variables, to improve readability of the if statements.
$post_type = isset( $_GET['post_type'] ) ? $_GET['post_type'] : '';
$notRequestMode=!isset( $_REQUEST['mode'] );
if( $post_type == 'faq' && $notRequestMode)
$_REQUEST['mode'] = 'excerpt';
// if I just go with else... it doesn't work
elseif( $post_type !== 'faq' && $notRequestMode)
$_REQUEST['mode'] = 'list';
There is a good chance you have a lot of $post_type
, so I would first set that within a switch
:
switch($post_type) {
case 'faq':
// code here
break;
case 'somethingElse':
// code here
break;
// etc.
From there, you could even nest another switch in for $_REQUEST['mode']
if appropriate, or just include your if
statements.
As a note on formatting, if I have a lot of conditions, I will put those conditions on multiple lines:
if (
$post_type == 'faq' &&
!isset( $_REQUEST['mode'] ) &&
// more conditions here
) {
Since you want short, here's short based on your example code.
if(!isset( $_REQUEST['mode'] )){
$_REQUEST['mode'] = 'list';
if($_GET['post_type']=="faq")
$_REQUEST['mode'] = 'excerpt';
}
Your actual code can be resolved to:
if (!isset($_REQUEST['mode'])) {
if (isset($_GET['post_type'])) {
$_REQUEST['mode'] = ($_GET['post_type'] == 'faq') ? 'excerpt' : 'list';
}
}
But is it really better? I mean, you're surely going back to your code some time in the future...
Try this
$post_type = isset( $_GET['post_type'] ) ? $_GET['post_type'] : '';
$_REQUEST['mode'] = !isset($_REQUEST['mode'])?(($post_type==='faq')?'excerpt':'list'):'';
In PHP 5.3+ you can use the shortened ternary:
$post_type = $_GET['post_type'] ?: '';
if (!isset( $_REQUEST['mode'] )) {
$_REQUEST['mode'] = $post_type == 'faq' ? 'excerpt' : 'list';
}
But the shortest is probably:
if (!isset( $_REQUEST['mode'] )) {
$_REQUEST['mode'] = isset($_GET['post_type']) && $_GET['post_type'] == 'faq' ? 'excerpt' : 'list';
}
Or on a single line with the shortened ternary:
$_REQUEST['mode'] = $_REQUEST['mode'] ?: (isset($_GET['post_type']) && $_GET['post_type'] == 'faq' ? 'excerpt' : 'list');