Arrays and Functions

Site Admin · 11 Sep 2026 · 6 views

Arrays and Functions

Arrays are PHP's all-purpose collection type, and functions package logic into reusable named blocks.

Indexed and associative arrays

$fruits = ['apple', 'banana'];
$user   = ['name' => 'Ada', 'age' => 36];
echo $fruits[0] . ' ' . $user['name'];

Indexed arrays use numeric positions; associative arrays use named string keys.

Useful array functions

array_push($fruits, 'cherry');
$total = count($fruits);
sort($fruits);
$has = in_array('apple', $fruits);

Defining functions

function add(int $a, int $b): int
{
  return $a + $b;
}
echo add(2, 3);

Parameters and return types are optional but document intent and enable strict checks.

Default values and named arguments

function greet($name, $lang = 'en') { ... }
greet('Ada');
greet(lang: 'fr', name: 'Ada');

Default values fill in missing arguments, and named arguments let callers skip the middle ones.

Variable scope

Variables inside a function are local. To read an outside variable, pass it in or use the global keyword explicitly. Returning values keeps functions pure and predictable.

Key Points

  • Arrays hold lists or key-value maps.
  • Array helper functions sort, count, and search.
  • Functions declare typed parameters and returns.
  • Defaults and named arguments make calls flexible.
  • Function scope keeps variables local.
Share this post:

Comments (0)

Please login or register to comment.