Skip to content

Instantly share code, notes, and snippets.

@matiskay
Created January 4, 2012 23:47
Show Gist options
  • Save matiskay/1562893 to your computer and use it in GitHub Desktop.
Save matiskay/1562893 to your computer and use it in GitHub Desktop.
PHP Tips and Tricks
<?php
// Short Ternary Operators
$var = 'SomeValue';
$output = $var ? $var : 'default';
$output = $var ?: 'default'; // PHP >= 5.3
// Directory Listing #3
$dir = 'application/modules/';
foreach(new DirectoryIterator($dir) as $fileInfo) {
echo "Filename is: " . $fileInfo->getFilename();
}
// Exploded String values
$string = 'bazinga.foo.bar.suitup';
$values = explode('.', $string);
$sheldon = $values[0]; //bazinga
$barney = $values[3]; //suitup
list($sheldon, , , $barney) = explode('.', $string);
// PHP 5.4 stuff
$sheldon = explode('.', $string)[0];
$barney = explode('.', $string)[3];
// File Path Information
$path = '/some/directory/in/filesystem/file.some.txt';
$fileInfo = pathinfo($path);
$fileInfo['dirname'] === pathinfo($path, PATHINFO_DIRNAME);
$fileInfo['basename'] === pathinfo($path, PATHINFO_BASENAME);
$fileInfo['extension'] === pathinfo($path, PATHINFO_EXTENSION);
$fileInfo['filename'] === pathinfo($path, PATHINFO_FILENAME);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment