41 PHP optimization tips

As with any tips for optimization, it’s best advised to benchmark your code first rather than just start hacking and slashing your code. With that said and understood, I enjoy reading articles for better optimizing PHP code and came across this one from reinholdweber with 40 tips + 1 bonus tip that looks pretty good. These items stuck out to me, but haven’t directly benchmarked all of them (yet, but I will be checking the ones I didn’t already learn) them to test:

12. Error suppression with @ is very slow.
13. $row[’id’] is 7 times faster than $row[id]
25. When echoing strings it’s faster to separate them by comma instead of dot. Note: This only works with echo, which is a function that can take several strings as arguments.
32. Learn to love the ternary operator.

Talk like a pirate text filter suite by Dougal Campbell

Today is Talk Like A Pirate Day. Appropriate day to implement Dougal Campbell’s text filter suite Wordpress plugin which includes the Talk Like a Pirate filter. Every post and every comment today only on September 19 will have the text converted to pirate speak.

It works with the most recent version of Wordpress, 2.2.3. To install on your blog, do the following:

1. copy the zzz_tts-core.php and tts-pirate.php to you wp-content/plugins directory
2. activate plugin.
3. have fun!

Wordpress, coded in PHP, powers the php-scripts blog.

Formatting numbers with sprintf

In the game Keno you might have noticed that games begin at 001 and iterate to 999. Let’s look at some code to cycle properly and stay formatted in three digits using sprintf().

$game_number = 1;
echo ‘Game #’ . sprintf(“%03d”,$game_number); // Game #00x
 

Now let’s add some style magic to give the output a blackground with red numbers:

$game_number = 1;
echo ‘New game #<font style="background-color: black;color: red">’ . sprintf(“%03d”,$game_number) . ‘</font><br />’;

Finally we need to create some program logic to test when to reset the game number to 1. An IF statement will suffice and we’ll also add some code to go to show the next game number.

$game_number = (int)$_GET[‘gid’];
if($game_number > 999 or $game_number < 1) {
$game_number = 1;
}
echo ‘New game #<font style="background-color: black;color: red">’ . sprintf(“%03d”,$game_number) . ‘<br />’;
$game_number++;
echo “<p><a href=\”?gid=$game_number\”>next game</a></p>”;

Date and time page last updated

A PHP one-liner to keep the date/time the page was last updated:

page last updated <?php echo date(“F d Y H:i:s”, getlastmod() ); ?>

Note: uses the server timezone by default. getlastmod() returns a timestamp and if you are on a shared server (virtual hosting) and cannot change the timezone, let’s say the timezone is off by two hours just use the following:

page last updated <?php echo date(“F d Y H:i:s”, (getlastmod() - 7200) ); ?>

PHP still #4 programming language, Ruby on the move in TIOBE index

The TIOBE Programming Community index tracks the popularity of different programming languages. Over the last year positions #1-6 have not changed with PHP holding at #4 behind Java (#1), C (#2) and C++ (#3).

PHP still #4

Heard a lot about Ruby over the last year or so? It moved from #21 to #11. Definitely on the move.

How to use MySQL REPLACE function

Here’s a MySQL query fuction that’s easy to forget about: REPLACE. Let’s say I have a bunch of records in a field with http://www and want to quickly change all to http://. Here’s the syntax to update:

UPDATE tdurl_1 SET URL = REPLACE(URL, ‘http://www.tdurl.com/’,'http://tdurl.com/’);

Yahoo has PHP programming positions available

Rasmus Lerdorf, creator of PHP, posts about PHP programming positions available at Yahoo:

Send me your resume and let me know what sort of stuff you are interested in or poke around on http://careers.yahoo.com/ and let me know which job interests you and I will forward your resume to the appropriate hiring manager.

Perl to PHP cheatsheet

Sooner or later you may want or need to port some Perl code to PHP. This Perl to PHP translation cheatsheet may come in handy.

How to build a how many days in the future script with timezone offset

This morning I was wondering what the date would be an arbitrary number of days in the future, like if somebody says: get back to me in a few months. I decided to search Google to see if there was a simple, web-based form that I could enter in the number of days in the future and my timezone and get returned the date/time in the future.

A couple variations of queries didn’t turn up anything that fit what I was looking for, so I decided to build my own and share the process here. For this project we’ll be using the following built-in PHP functions:

count - get the size of the timezonelist array
time - get timestamp
strtotime - add form submitted amount of time
date - format the date
putenv - change timezone

Data needed
List of timezones inserted into a sorted array. I’ve done the work here and provide in an array called $timezonelist. This will be used in the dropdown input form so the person using can set to their timezone.

Security concerns
To prevent users from entering in bogus timezones we’ll tie to a valid array index and check before using putenv() to change.

STEP 1. Add a comment header to explain the code and licensing terms:

<?php
/* Created: 12/21/2006
daysinfuture2.php -> original code by TDavid @ tdscripts.com
License: Creative Commons 2.5 Attribution
Desscription: Enter in days in the future and find out the date
*/

STEP 2. Add the sorted time zone list array and determine the array size using the count function. Due to the size of the array, I’m including only a couple entries in the code below. You’ll be able to view the entire array at the end of this post.

$timezonelist = array(‘Africa/Abidjan’,‘Africa/Accra’); // incomplete timezone list, example only
$sizetz = count($timezonelist);

STEP 3. Handle the input from the form submit, if any and validate the input as integers. The maximum number of days allowed into the future is 10,000.

$fdays = (int)$_POST[‘d’]; // number of days entered from form
$ftz = (int)$_POST[‘tz’]; // timezone chosen from

// 10,000 days max
if($fdays &lt;0 || $fdays >10000) {
$fdays = 7; // week from now is default
}

// default timezone is Los Angeles / PST
if($ftz > $sizetz || $ftz < 0) {
$ftz = 107; // default timezone PST
}

STEP 4. Set the timezone using the index in the timezonelist array chosen by the person submitting the form or the default if an invalid or no selection was made.

putenv(“TZ=$timezonelist[$ftz]”);

STEP 5. Get the current time and calculate the number of days into the future.

$today = time();
$future_tense = strtotime(“+$fdays days”, $today);

STEP 6. Output to the browser the current formatted date/time and future date/time. Then close the PHP script.

print “Now: “ . date(“l M d, Y H:i:s”, $today) . ” <i>$timezonelist[$ftz]<br /><font color=\”green\”><b>+ $fdays days =</b></font> <b>” . date(“l M d, Y H:i:s”, $future_tense) . ‘</b>’;
?>

STEP 7. Create the first part of the form for the person to submit to the script the days into the future and timezone. At the top of the list select the USA Los Angeles time (PST) as default. The values for the options are the index position in the timezone array.

<form method=“POST” action=“daysinfuture2.php”>
Number of days in the future? <input type=“text” size=“3″ name=“d” value=“<?php echo($fdays);?/>"> Timezone? (pending)
<select name=”tz“>
<option SELECTED value=”107“>USA - Pacific (GMT -8)</option>
<option value=”70“>USA - Midwest (GMT -6)</option>
<option value=”122“>USA - Eastern (GMT -5)</option>

STEP 8. Dynamically generate all sorted timezones from the array.

<?php
for($y=0;$y<$sizetz;$y++) {
        print(“<option value=\”$y\”>$timezonelist[$y]\n);
}
?>

STEP 9. Now close the HTML form code and we’re done.

</select> <input type=“submit” value=“See future date”/>
</form>

Test execution of daysinfuture2.php
Complete source code

How to randomize, return and remove numbers from a pool

This morning in the IRC chat (irc.scriptschool.com #scriptschool) a random visitor named Rnd-Amarion stopped by with the following how-to PHP question:

I am about to learn PHP, and want to program a simple web page with a long string of random numbers. I have the random numbers allready. When someone queries the web site, it retrieves four of those numbers from the front of this list and gives them to the querier and then removes those numbers form the front fo the list.

I asked him what were the range of numbers he wanted randomized. While this information wasn’t critical to writing the code to solve this how-to, it would better demonstrate to him (her? I didn’t ask). Didn’t get a response but I decided to help this unknown person anyway.

Let’s consult the PHP manual for the function array_rand (PHP 4, 5) and the definition:

array_rand — Pick one or more random entries out of an array

That sounds like the right function, but with most programming languages there are many ways to approach the same problem. Let’s create some code to do this using the PHP functions range, shuffle and array_shift.

$random_numbers = range(1,100);
shuffle($random_numbers); // mix up the order
// return the first four numbers when queried and remove from array
$numbers_chosen = array($random_numbers[0], $random_numbers[1], $random_numbers[2], $random_numbers[3]);

print “Before: <br />”;
print_r($random_numbers); // show all random numbers

// remove first four numbers
for($i=0;$i&lt;4;$i++) {
array_shift($random_numbers);
}

print“<hr />After: “;
print_r($random_numbers); // show all remaining random numbers
print“<hr />Chosen: “;
print_r($numbers_chosen); // first four numbers chosen
 

Example: code execution, code source

Notes: The array_shift function removes the first item in an array. The converse array_pop removes the last item in an array. Another useful array function is array_splice.

Update 9:55am PST: You can see a more efficient version using array_splice here that eliminates the use of the for loop in the code above and the use of array_shift. As for which is more efficient for removing only one item in the array, that’s a test for you to run :)

» Pages (999999) : 1 2 ... Last »