Single quote vs double quote

The double quote could have the variable inside.

$name = 'Eric';
$greeting1 = "Hello $name";
$greeting2 = 'Hello $name';
echo $greeting1; // Hello Eric 
echo $greeting2; // Hello $name 

Iterator in php

  • Use glob to get file names in the system.
$theme_path = '/theme/path';
foreach (glob($theme_path . "/preprocess/*.inc") as $file) {
  require_once $file;
}
  • Use array_map function to call a function multiple times, every time one element will be assign as parameter.
// Drupal 'theme' function will get the corresponding template back.
// The result will be stored in array.
$rendered_html = array_map('theme', [
    'theme1',
    'theme2',
    'theme3',
]);
  • Use array_reduce function to call a function iteratively, reduce the array to single value.

  • Use array_merge function to override default value in array (e.g. extend/override configuration).

  $block_default = ['cache' => DRUPAL_NO_CACHE, 'category' => t('CATEGORY')];
  $blocks['BLOCK1'] = array_merge($block_default, [
    'info' => t('BLOCK ONE'),
  ]);
  $blocks['BLOCK2'] = array_merge($block_default, [
    'info' => t('BLOCK TWO'),
  ]);
  $blocks['BLOCK3'] = array_merge($block_default, [
    'info' => t('BLOCK THREE'),
  ]);
  • Use array_fill_keys to assign same value to all the elements in an array
$keys = array('Batman', 'Superman', 'Spiderman', 'Ironman');
$a = array_fill_keys($keys, 'Marvel Comics');
  • Use array_filter to remove the empty value.

Type Conversion

// Use type conversion to make the function accept both number and array as data type.
function foo_bar($arg1) {
  $result = 0;
  foreach ((array) $arg1 as $value) {
      $result += $value;
  }
  return $result;
}
print foo_bar(1);     // Output 1.
print foo_bar([2,3]); // Output 5.

Require vs include

require is identical as include, except it can throw error when failure.

require_once will check if the file has already been included.

Isset vs empty vs isnull

  • isset return true when the variable is not null

  • empty return true when the variable is an empty string / false / array() / null / 0 and a unset value.

  • isnull is opposite as isset, return true when null

Some Utility Sample

  • Get function with the default value
function _get(&$var, $default = NULL) {
  return !empty($var) ? $var : $default;
}
  1. sorting