Declarative vs imperative programming

Published on March 23rd, 2024

Imperative programming is a way to write code by explaining every step needed to get the result. This type of programming heavily relies on loops such as for and while , and on conditionals.

Declarative programming tends to declare the end result. Instead of focusing on how to do something, I tell the computer what I want to achieve.

Imperative example

$items = ['banana', 'strawberry', 'orange', 'lemon'];

// get items that have more than 5 chars
$filteredItems = [];
foreach($items as $item) {
	if(strlen($item) > 5) {
		$filteredItems[] = $item;
	}
}

In imperative programming, tell the computer what to do to get me where I want. In the above example, I start with an empty array and loop over the array. If an item matches our logic, I put it in the array. I list every step needed for the computer to understand what it needs to do.

Declarative example

$items = ['banana', 'strawberry', 'orange', 'lemon'];

// get items that have more than 5 chars
$filteredItems = array_filter($items, fn($item) => strlen($item) > 5);

In declarative programming, declare what the final results should be, not how to do it. This leads to less code and better readability. There are some native declarative methods in PHP, especially those handling arrays, such as array_filter(), array_reduce() and array_map().

Eloquent methods and Laravel helpers are often declarative.

$user = User::where('name', 'Zuzana')->get()->first(); is a declarative way to fetch a user in Laravel.

SQL has a declarative syntax, using keywords such as CREATE, SELECT or WHERE.

Quick tip - If you can read the code as a sentence, it's probably declarative.

← Go back