Free Online Toolbox for developers

Handy PHP Tips and Tricks: Operators and functions to know

Yield keyword

The “yield” operator in PHP is a powerful tool used to produce a sequence of values. Instead of returning all the values at once, “yield” allows the function to yield each value as it is requested, resulting in more efficient memory usage. Here’s a concise example:

function generateNumbers() {
    yield 1;
    yield 2;
    yield 3;
}

foreach (generateNumbers() as $number) {
    echo $number . " ";
}
// Output: 1 2 3

Consider a scenario where you need to load one million rows of data from a database. The traditional approach of loading all the data at once can be memory-intensive and may impact the performance of your application. However, with the help of the “yield” operator, you can overcome these challenges and maintain a clean and efficient codebase. By using the “yield” operator in a generator function, you can fetch and process the data gradually, one row at a time. This allows you to conserve memory resources and ensures that your code remains concise and easy to understand. The “yield” operator proves to be a valuable tool in handling large datasets without compromising code simplicity and clarity.

Array functions

There are numerous PHP functions available for manipulating arrays. Let’s take a brief look at some of my favorite functions that I find particularly useful for array manipulation.

array_map()

The array_map function transforms array elements by applying a callback function. It’s a handy tool for efficient array manipulation.

// multiplying each element by 2

$myTab = array_map( function($x) { return $x * 2; }, [1, 2, 3] );

echo json_encode  ( $myTab ); // Output [2, 4, 6] 

array_filter()

The array_filter function selectively filters array elements based on a callback function. It’s great for removing unwanted elements from an array.

// keeping only the even numbers

$myTab = array_filter([1, 2, 3, 4, 5], function($x) { return $x % 2 === 0; });

echo json_encode  ( $myTab ); // Output [2, 4] 

Concise code

Personally, I like concise code.

Nullsafe operator 

The Nullsafe operator provides a safe way to access properties or methods on potentially null objects. It simplifies code and reduces null-related errors.

// With Nullsafe operator
$address = $user?->getProfile()?->getAddress();

// Without Nullsafe operator
if ($user !== null && $user->getProfile() !== null && $user->getProfile()->getAddress() !== null) {
    $address = $user->getProfile()->getAddress();
} else {
    $address = null;
}

Null Coalescing Operator

The null coalescing operator offers a concise way to handle null values. It allows you to provide a default value if a variable is null.

// With Coalescing operator
$name = $username ?? 'Guest';

// Without Coalescing operator
$name = isset($username) ? $username : 'Guest';
// Or worse
if (isset($username)) {
    $name = $username;
} else {
    $name = 'Guest';
}

Arrow functions

Arrow functions introduce a more compact syntax for writing anonymous functions. They provide a shorthand way to define functions without the need for the “function” keyword.

$addition = fn($a, $b) => $a + $b;

Constructor property promotion

Less boilerplate code to define and initialize properties.

class User {
  public function __construct(
    public int $id = 0,
    public string $firstname = null,
    public string $lastname = null,  
  ) {}
}



Leave a Reply