Originally published on zero2php.dev — part of the Zero to PHP course. View this lesson on the original site.
Everyday tasks
Common tasks you will do constantly:
- Add:
$items[] = 'new';or$items['key'] = 'value'; - Remove:
unset($items[1]);(be careful with re-indexing for lists) - Count:
count($items) - Sort:
sort,ksort,asort(each behaves differently—read the docs)
Example
<?php
declare(strict_types=1);
$scores = ['ada' => 95, 'linus' => 88];
arsort($scores);
print_r($scores);
Debugging
When something looks “weird”, print_r or var_dump the array before guessing.
Exercise
Set $nums = [3, 1, 2], sort it ascending, then echo the three digits concatenated (no spaces)—output 123.
From Zero to PHP — Control flow, functions, arrays, and the web