← 講座に戻る: PHP from scratch

Arrays and week 3 review

動画は近日公開

An array is a variable that holds several values. It is the central data structure of PHP: a list of products, an application's configuration, a database row or the data coming from a form are all arrays. PHP has a single array type that serves two uses: lists (numeric keys 0, 1, 2…) and dictionaries or associative arrays (text keys). In this lesson you will learn to create, read, modify and walk through them, and review what you saw this week.

Lists and associative arrays

They are created with square brackets. In a list, PHP numbers the elements from 0. In an associative array, you choose the keys with the arrow =>. To read an element you use $array[key]. If the key does not exist you get a warning (Warning: Undefined array key), which is why it is common to combine access with ?? to give a default value. To append an element to a list use $list[] = value; to delete one use unset($array[key]).

php
<?php

declare(strict_types=1);

$fruits = ['apple', 'banana', 'cherry'];
$fruits[] = 'grape';              // append
echo $fruits[0], "\n";            // apple
echo count($fruits), "\n";        // 4

$user = [
    'name' => 'Ana',
    'email' => 'ana@example.com',
    'roles' => ['admin', 'editor'], // nested array
];
echo $user['name'], "\n";         // Ana
echo $user['roles'][1], "\n";     // editor
echo $user['phone'] ?? 'no phone', "\n"; // no phone

unset($user['email']);
var_dump(isset($user['email']));  // bool(false)
var_dump(array_key_exists('name', $user)); // bool(true)

Walking arrays and useful functions

With foreach you walk any array. PHP also includes dozens of ready-made functions. The most common: count (how many elements), in_array (does this value exist?), array_keys and array_values, array_merge (join arrays), array_slice (cut), sort and rsort (order a list), ksort (order by key) and implode / explode to convert between array and text. Careful: sort modifies the original array and returns a boolean, not the sorted array. To avoid surprises, use in_array with the third argument true, which enables strict comparison.

php
<?php

declare(strict_types=1);

$stock = ['pen' => 40, 'book' => 0, 'ruler' => 12];

foreach ($stock as $item => $qty) {
    $status = $qty > 0 ? "$qty units" : 'sold out';
    echo "$item: $status\n";
}
// pen: 40 units
// book: sold out
// ruler: 12 units

$numbers = [5, 3, 9, 1];
sort($numbers);                       // modifies $numbers in place
echo implode(', ', $numbers), "\n";   // 1, 3, 5, 9

var_dump(in_array('3', $numbers, true)); // bool(false) - strict
var_dump(in_array(3, $numbers, true));   // bool(true)

$parts = explode(',', 'a,b,c');
print_r($parts); // Array ( [0] => a [1] => b [2] => c )

Arrays can contain other arrays, and that is how real data is modeled: a list of users where each user is an associative array with name, email and roles. To walk them you nest foreach loops, one inside another. Two handy operators: the spread (...) which expands one array inside another, and destructuring, which spreads values into variables with [$a, $b] = $list. When a function receives an array, it receives a copy: if you change it inside, the original does not change, unless you use a reference.

理解度チェック

問題 1 / 6

What does $list[] = 7; do?

✎ マイノート

このブラウザにのみ保存されます。ログインするとアカウントに保存できます。0/5000 文字

← 前へ次へ →