Dorokhov.codes
Tricks
To check if specified keys exist in some another array:
$looking_for = [ 'one', 'two', 'three' ];
$all_keys_exist = ! array_diff_key( array_flip( $looking_for ), $array );
Shorthand ternary operator syntax:
// We can use:
$type = $initial ?: 'writer';
// Instead of:
$type = $initial ? $initial : 'writer';
Compact function:
# Instead of:
view('home', ['name' => 'Andrew', 'city' => 'Kyiv']);
# Using compact():
view('home', compact('name', 'city'));
Instead of using isset()
:
$output = $input['key'] ?? 'fallback';
// Instead of:
$output = isset($input['key']) ? $input['key'] : 'fallback';
Operators
Ternary operator:
// Instead of:
if ($condition) {
$result = 1;
} else {
$result = 2;
}
// Use this:
$result = $condition ? 1 : 2;
Ternary shorthand:
// Instead of:
$result = $condition ? $condition : 2;
// Use this:
$result = $condition ?: 2;
// $condition - should be the same expression we put into if().
Files
Generate a unique file name for a temporary file.
$unique_filename = time() . '_' . bin2hex(random_bytes(6));
$full_path = sys_get_temp_dir() . "/$unique_filename";
With an extension:
$image_url = 'https://example.com/path/to/your/image.jpg';
$file_extension = pathinfo($image_url, PATHINFO_EXTENSION);
$unique_filename = uniqid() . '.' . $file_extension;
Strings
Generate a random string:
// First variant:
substr(md5(microtime()), 0, 6);
// Second variant:
bin2hex(random_bytes(6));
Generate a random string in Yii2:
// pattern [A-Za-z0-9_-]+
\Yii::$app->security->generateRandomString(7);