10 PHP One-Liners That Will Save You Hours of Coding
PHP is a versatile and powerful scripting language, loved by web developers for its simplicity and flexibility. In this article, we showcase 10 PHP one-liners that can make your development workflow smoother and save you hours of coding time. Whether you're a beginner or a seasoned developer, these snippets are sure to come in handy.
1. Convert a String to an Array
$array = explode(',', 'apple,banana,orange');
print_r($array);
// Output: Array ( [0] => apple [1] => banana [2] => orange )
2. Check if a String Contains a Substring
echo strpos('Hello World', 'World') !== false ? 'Found' : 'Not Found';
// Output: Found
3. Get the Current Timestamp
echo time();
// Output: 1633739182 (varies depending on the current timestamp)
4. Create a Simple Autoloader
spl_autoload_register(fn($class) => require_once "$class.php");
5. Fetch Data from a JSON API
$data = json_decode(file_get_contents('https://api.example.com/data'), true);
print_r($data);
6. Generate a Random String
echo bin2hex(random_bytes(8));
// Output: a random 16-character string
7. Calculate the Difference Between Two Dates
$diff = (new DateTime('2024-01-01'))->diff(new DateTime('now'))->days;
echo "$diff days left till 2024";
8. Send a Simple Email
mail('recipient@example.com', 'Subject', 'Message');
// Sends a basic email
9. Flatten a Multidimensional Array
$flat = iterator_to_array(new RecursiveIteratorIterator(new RecursiveArrayIterator($array)), false);
10. Check if a File Exists
echo file_exists('example.txt') ? 'File exists' : 'File not found';
Conclusion
These one-liners illustrate PHP's flexibility and efficiency. Mastering such concise solutions will not only save you time but also improve your coding efficiency. Do you have a favorite PHP one-liner? Share it in the comments!