VS Vikesh Singh

Courses PHP & Laravel Lesson 3

PHP & LARAVEL · LESSON 3 OF 18

Arrays and Strings: The PHP Functions You'll Use Daily

· 5 min read

Variables, functions, and control flow from lesson 2 give you the grammar.

Variables, functions, and control flow from lesson 2 give you the grammar. Arrays and strings are what you actually spend your day manipulating in real PHP code, whether that is plain PHP or Laravel. This lesson is deliberately practical: these are the specific functions you will reach for constantly, not a complete reference of everything PHP offers.

Arrays In PHP

PHP has one array type that does double duty as both what other languages call a list (sequential, numerically indexed) and what other languages call a dictionary or map (string keys pointing to values). This is unusual compared to languages like Python or JavaScript, which have separate list and dict/object types, and it is worth understanding clearly because Laravel's Eloquent results and configuration files lean on this constantly.

$heroes = ["Iron Man", "Captain America", "Thor"];

$heroProfile = [
    "name" => "Tony Stark",
    "alias" => "Iron Man",
    "age" => 48,
];

echo $heroes[0];              // Iron Man
echo $heroProfile["alias"];   // Iron Man

The first array, with no explicit keys, gets numeric keys automatically starting at 0. The second, called an associative array, uses strings as keys. You can mix both styles in the same array, and you will see this constantly in Laravel: a list of records where each record is itself an associative array of column names to values.

Looping With Foreach

Looping over arrays uses foreach, and it has two forms worth knowing. The simple form gives you just the value; the second gives you the key and value together, which matters the moment you are working with an associative array:

foreach ($heroes as $hero) {
    echo $hero . "\n";
}

foreach ($heroProfile as $field => $value) {
    echo "{$field}: {$value}\n";
}

Everyday Array Functions

Now the functions you will actually use every day. array_map transforms every element of an array using a function you supply, and returns a new array without touching the original:

$prices = [100, 250, 75];

$withTax = array_map(function (int $price): float {
    return $price * 1.18;
}, $prices);

// $prices is unchanged, $withTax is [118.0, 295.0, 88.5]

array_filter keeps only the elements for which your function returns true, and array_reduce collapses an entire array down into a single value by applying a function repeatedly, carrying an accumulator forward:

$trades = [
    ["symbol" => "NIFTY", "pnl" => 1200],
    ["symbol" => "NIFTY", "pnl" => -300],
    ["symbol" => "BANKNIFTY", "pnl" => 800],
];

$winners = array_filter($trades, fn ($trade) => $trade["pnl"] > 0);

$totalPnl = array_reduce($trades, function (float $carry, array $trade): float {
    return $carry + $trade["pnl"];
}, 0.0);

// $totalPnl is 1700.0

That fn ($trade) => $trade["pnl"] > 0 is an arrow function, PHP's shorthand for a short, single-expression closure. It automatically captures variables from the surrounding scope (unlike the older function() use ($var) {} closure syntax, where you had to list captured variables explicitly), and it is the standard choice for short callbacks like this one. Save the longer function (...) {} form for callbacks that need more than one line or need explicit control over what gets captured.

A genuinely common and costly mistake: calling array_map, array_filter, or similar functions inside a loop, on every iteration, when they could be computed once outside the loop. These functions each walk the entire array every time you call them; calling one of them 10,000 times inside another loop, instead of once, is an easy way to turn a fast script into a slow one, and it is one of the first things worth checking when a PHP script that processes a lot of data is running slower than expected.

Everyday String Functions

String functions deserve equal attention, because every web application spends enormous amounts of time formatting, checking, and transforming strings. The essentials:

$email = "  VIKESH@Example.com  ";

$clean = strtolower(trim($email));
// "vikesh@example.com"

$isValid = str_contains($clean, "@");
// true

$parts = explode("@", $clean);
// ["vikesh", "example.com"]

$rebuilt = implode(" at ", $parts);
// "vikesh at example.com"

$padded = str_pad((string) 7, 3, "0", STR_PAD_LEFT);
// "007"

trim removes whitespace from both ends of a string, which matters more than it sounds like it should: user-submitted form data almost always has stray leading or trailing spaces, and comparing an untrimmed string against a database value is a classic source of "this should match but doesn't" bugs. explode splits a string into an array on a delimiter; implode does the reverse, joining an array back into a string. str_contains, added in PHP 8, replaced the old and genuinely confusing pattern of checking whether strpos($haystack, $needle) was not false (confusing because strpos can legitimately return 0 for a match at the very start of the string, and 0 is falsy, so the old check needed !== false specifically, not just a truthiness check). If you ever see strpos(...) !== false in older PHP code, that is exactly what it is working around; str_contains makes the intent obvious.

Common Mistakes To Avoid

One more distinction that matters for correctness, not just style: == vs === from lesson 2 applies to strings too, and string-to-number comparisons are a real source of bugs. "100" == "1e2" is true because PHP converts both to the number 100 for comparison when the strings look numeric. If you are comparing two things that are conceptually strings, like two trading symbols or two slugs, always use ===, never ==.

A closing habit worth adopting now: reach for array_map, array_filter, and array_reduce before reaching for a hand-written foreach loop with a temporary accumulator variable, whenever the transformation is simple enough to express in one line. Not because loops are wrong, they are perfectly readable for anything multi-step, but because array_filter($trades, fn ($t) => $t["pnl"] > 0) tells a reader exactly what it does on first read, while a five-line loop with an if and a running array forces them to simulate the loop in their head to reach the same conclusion. Readability, not cleverness, is the actual reason experienced PHP developers favor these functions for short, single-purpose transformations.

Try it yourself: take an array of associative arrays representing trades (symbol, quantity, price), use array_filter to find all trades above a certain price, array_map to compute a value field for each (quantity * price), and array_reduce to sum the total value, chaining all three together on one array.