.Tech Leaderboard

Xerox Tech Support

Revealing the Tech World

PHP Optimization Techniques

At the point when composing classes in PHP, you can spare time and accelerate your scripts by meeting expectations with item properties specifically, as opposed to composing innocent setters and getters. In the accompanying case, the
dog class uses the setName() and getName() methods for accessing the name property.

class dog {
public $name = ”;

public function setName($name) {
$this->name = $name;

public function getName() {
return $this->name;

Notice that setName() and getName() do nothing more than store and return the name property, respectively.

$rover = new dog(); $rover->setName(‘rover’); echo $rover->getName();

Setting and calling the name property directly can run up to 100% faster, as well as cutting down on development time.

$rover = new dog();
$rover->name = ‘rover’;
echo $rover->name;

Don’t copy variables for no reason

Sometimes PHP novices attempt to make their code “cleaner” by copying predefined variables to variables with shorter names before working with them. What this actually results in is doubled memory consumption (when the variable is altered), and therefore, slow scripts. In the following example, if a user had inserted 512KB worth of characters into a textarea field. This implementation would result in nearly 1MB of memory being used.

$description = strip_tags($_POST[‘description’]);
echo $description;

There’s no reason to copy the variable above. You can simply do this operation inline and avoid the extra memory consumption:

echo strip_tags($_POST[‘description’]);

Avoid doing SQL queries within a loop

A common mistake is placing a SQL query inside of a loop. This results in multiple round trips to the database, and significantly slower scripts. In the example below, you can change the loop to build a single SQL query and insert all of your users at once.

foreach ($userList as $user) {
$query = ‘INSERT INTO users (first_name,last_name) VALUES(“‘ . $user[‘first_name’] . ‘”, “‘ . $user[‘last_name’] . ‘”)’;


INSERT INTO users (first_name,last_name) VALUES(“John”, “Doe”)

Instead of using a loop, you can combine the data into a single database query.

$userData = array();
foreach ($userList as $user) {
$userData[] = ‘(“‘ . $user[‘first_name’] . ‘”, “‘ . $user[‘last_name’] . ‘”)’;
$query = ‘INSERT INTO users (first_name,last_name) VALUES’ . implode(‘,’, $userData);


INSERT INTO users (first_name,last_name) VALUES(“John”, “Doe”),(“Jane”, “Doe”)…;

Leave a Reply

Your email address will not be published. Required fields are marked *