Skip to content

Instantly share code, notes, and snippets.

@hellofromtonya
Created March 13, 2017 18:26
Show Gist options
  • Save hellofromtonya/bb69ccd9a9e58b207ae667f9a01d3d9a to your computer and use it in GitHub Desktop.
Save hellofromtonya/bb69ccd9a9e58b207ae667f9a01d3d9a to your computer and use it in GitHub Desktop.
Some PHP ternary examples
<?php
/***************************
* Ternary Examples
**************************/
/**
* Determine whether the given value is array accessible.
*
* @since 1.0.0
*
* @param mixed $value
*
* @return bool
*/
function is_array_accessible( $value ) {
/**
* Long-hand version: using an if/else structure
* i.e. the `else` is implied
*/
if ( is_array( $value ) ) {
return true;
}
return $value instanceof ArrayAccess;
/**
* Short-hand structure using a ternary
*/
return is_array( $value )
? true
: $value instanceof ArrayAccess;
}
function array_get( array $subject_array, $go_deep = false, $default_value = null ) {
/**
* Long-hand structure to make an assignment using
* an if/else structure.
*/
if ( $go_deep ) {
$array_walk_function = 'array_walk_recursive';
} else {
$array_walk_function = 'array_walk';
}
// go do the work now.
/**
* Short-hand structure using a ternary
*/
$array_walk_function = $go_deep
? 'array_walk_recursive'
: 'array_walk';
// go do the work now.
}
/***************************
* SMELLY CODE ALERTS
**************************/
function smelly_code_example( $value ) {
/**
* Smelly code pattern is when you literally return a true or
* false based upon a conditional expression.
*
* Why? Because the `is_array()` conditional expression already
* returns true or false.
*/
if ( is_array( $value ) ) {
return true;
}
return false;
/******
* This is smelly too
*/
return is_array( $value )
? true
: false;
}
function better_solution( $value ) {
/**
* Better solution is to just return the conditional
* expression. Why?
*
* 1. Less code
* 2. Faster
* 3. More readable
*/
return is_array( $value );
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment