Tech Talk : PHP - Nifty & Nice Part 01

Tech Talk : PHP - Nifty & Nice Part 01

Xybernetics PHP Programming Tips Nifty and NiceHere are some of the collection of cool coding techniques in PHP and at times in other programming platform from all around the web. Hope you enjoy it.

Array – Best way to clear a PHP array values.
Use unset, if you need the array later on just instantiate it again.

unset($foo);
$foo = array();

Array – Return an array from a function.
If you have a function and you would like to return multiple values from it, then you would code like this.

function someFunc( ) {
  $aVariable = 10;
  $aVariable2 = 20;
  return array($aVariable, $aVariable2);
}

And to retrieve the values returned from a function, you would use this code.

list($var1, $var2) = SomeFunction( );
echo "$var1 $var2";  // Print out the values

Value from $aVar1 is assigned to $var1 and value from $aVar2 is assigned to $var2.

Alternatively, you can store it as an array.

$returnVar = SomeFunction();
echo $returnVar[0];
echo $returnVar[1];

Value from $aVar1 is assigned to $returnVar[0] and value from $aVar2 is assigned to $returnVar[1].

Shorthand If/Else in PHP
.
Basic True/False Declaration

$returnVar = SomeFunction();
echo $returnVar[0];
echo $returnVar[1];

Conditional Greeting Message

echo 'Hello '.($user['isLoggedIn'] ? $user['useFirstName'] : 'Guest').'!!';

Conditional Error Reporting Level

error_reporting($WEBSITE_IS_LIVE ? 0 : E_STRICT);

Conditional Basepath

echo '<base href="http'.($PAGE_IS_SECURE ? 's' : '').'://www.xybernetics.com" />';

Nested PHP Shorthand

echo 'Your grade is '.($grade > 10 ? ($age > 10 ? 'Average' : 'Exceptional') : ($age > 10 ? 'Horrible' : 'Average') );

Leap Year Check

$isLeapYear = ((($year % 4) == 0) && ((($year % 100) != 0) || (($year %400) == 0)));

Conditional PHP Redirect

header('Location: '.($valid_login ? '/users/index.php' : 'login.php?errors=1')); exit();

Reference

Leave a reply

Your email address will not be published. Required fields are marked *