Page 6 of PHP Articles

How to Output Variables within Strings with PHP

Displaying strings isn’t that hard, you just use echo followed by the string in question. But that only gets us so far, what about when we need to use variables inside of the string? Luckily there’s a ton of different ways to accomplish this. echo You can easily use echo […]

How to Use Colors in Command-line PHP Output

Nothing spruces up command-line output the way colors do. Just like when you’re customizing your [Bash] prompt, you can use color codes in strings to colorize your output. Keep in mind, these colors will only work on the command-line and not in a browser. First let’s take a look at […]

How to Compare Numeric Variables with PHP

Comparing numeric values is a very common programming task. Which number is greater? is lesser? equal? In PHP like any C-style language, you can do these comparisons with a simple if ( ... ) { ... } statement: if ($var1 > $var2) { echo $var1 . ' is greater than […]

How to check if a variable is an integer with PHP

PHP has a variety of functions and approaches to determine if a variable is a number and/or an integer. The problem is that many of the straight forward approaches can result in false positives depending on how they react to type juggling. Case in point, is_int() will return false for […]

How to Strip Whitespace from a String with PHP

Whitespace, it can make all the difference in the world when attempting to determine if a string is empty or not. Anytime you are working with user input I recommend stripping whitespace from both sides of the string. When stripping whitespace you can choose to strip from both sides or […]

How to Increment / Decrement a Number with PHP

Incrementing and decrementing a variable can be accomplished with C-style pre- and post-operators. The pre-operators return the value after it as been incremented or decremented, post- return the value before. Let’s take a look at incrementing first: $i = 1; echo ++$i; // outputs 2 echo $i++; // also outputs […]

While you were out - while loops in PHP

while loops are considered the simplest type of loop in PHP-dom. Their purpose is to continue to execute until a condition has been met. Let’s look at an example related to the title, a pseudo-script that will collect messages while you’re out, returning at 1pm (like a lunch break ;): […]

New Lines in Command-line PHP Output

If you’ve ever worked with command-line PHP and outputted text you know that PHP takes absolutely no liberties with injecting line breaks into the output. There’s also no magic function or configuration variable that will adjust this behavior. Easy enough, you want line breaks, just add them! echo "I am […]

How to Output Strings in PHP

Outputting strings is one of the most common actions when building a web site, and PHP offers a multitude of ways to do so each with their own set of strengths and weaknesses print print is a language construct and not a function, so you don’t need any parenthesis to […]

How to Capture User Input from Command-line PHP

When using command-line PHP capturing input is a bit different than when building a web application. Instead of building a form and interrogating some variables, you have to actually prompt the user for the input and then analyze it to determine if what the user input was what you were […]

How to Generate a Random Number with PHP

Generating a random number in PHP is very simple and like most things, can be done a number of different ways. The old standby is to use the function rand() to to generate a random integer between the minimum and maximum values that you provide. To generate a number between […]

Using Transactions with PHP Data Objects (PDO)

With PHP Data Objects, transactions are pretty simple. To be able to use a transaction, you simply wrap your queries with a call to beginTransaction() and either use commit() or rollBack() at the end. Rolling back is at your discretion but the easiest implementation would be to wrap the queries […]

How to Use Prepared Statements in PHP

Now that we know how to create a connection to our database using PHP Data Objects, let’s talk a bit about prepared statements. Now I’d like to think that we’ve all made this mistake before, taken user input and used it in an SQL query something like this: $db->execute('SELECT * […]

How to Connect to a Database with PHP Data Objects (PDO)

PHP Data Objects (PDO) provide a consistent interface to different databases including MySQL, PostgreSQL, SQLite, SQL Server and a handful of other systems as well. Aside from database-specific SQL, the only other thing that isn’t consistent is how to connect to a database. Each database type requires a string to […]

Split a String by Letters with PHP

Every once in a blue moon you find yourself needing to take a string and converting it to an array of characters in the string. Maybe it’s because you want to count how often certain letters exist in the string or want to convert the letters to something else. To […]

Passing Arguments to Command-Line PHP

In a previous post we discussed how to tell whether or not you are on the command-line from within your PHP script. Today we’re going to talk about passing command-line arguments to your script. When on the command-line two variables are available to you, $argc and $argv. They are the […]

Calculating page load time / execution time with PHP

So who remembers back in the day when one of the coolest things you could have on your website’s footer was the page load time? As passé as that may seem in this day in age, it’s still something that can be useful when attempting to profile a site or […]

Check if PHP is running from the command-line

When running PHP from the command-line interface, the availability of some variables and functionality may or may not be available. Case in point, when running command-line PHP sessions are not available and $_SESSION is undefined. When you’re on the command-line there’s also the possibility that you want to use the […]

Check if a PHP class exists

We’ve discussed how to check if a class has a function but what if the class doesn’t exist at all? To check if a class exists you can use, use guessed it, class_exists(). if (class_exists('MyClass')) { $object = new MyClass(); } else { throw new Exception('The class MyClass does not […]

Check if a PHP class has a certain function

We’ve previously discussed how to check if a function exists but that only works on standalone functions like the ones built into PHP as well as any user defined functions. Luckily there’s a function for that called method_exists(). When speaking in the scope of a class, the functions are referred […]

Check if a PHP function exists

Let’s use json_encode as an example here. Prior to PHP 5.2.0 JSON support was only available via a PECL extension and since 5.2.0 it’s been available as part of the PHP core. You could check that the server is running PHP 5.2.0 or above, but that could result in a […]

Detect Required PHP Version

If you write and/or use open source software, you know that running an up to date version of PHP is a must. This can be a problem sometimes, like if you are running on a host that doesn’t run the most up to date version of PHP. Another scenario would […]

Convert Errors to Exceptions in PHP

I was having a conversation with a buddy of mine the other day and we got on the topic of PHP not having a very standardized error system. Now that he’s working with Python the mix of errors and exceptions in PHP is an apparent shortcoming. PHP is funny like […]

Speed up PHP with APC

The Alternative PHP Cache (APC) is a PECL package that provides an opcode cache for PHP. Rasmus Lerdorf is the lead of the project along with a handful of other developers. What is an opcode cache? Before I can answer that, let’s discuss how PHP works. Because it is an […]

How to Build a Leaderboard with PHP and Redis

One of biggest draws to Redis for me is the fact that it has more data structure types than just key / value. These additional data structures allow you to do some amazing things while still benefitting from being in-memory. One of the most notable ways to leverage Redis would […]