Create and loop through arrays

Indexed and associative arrays, adding items and looping with foreach.

PHP · Create and loop through arraysBeginner
$colors = ['red', 'green'];
$colors[] = 'blue';                     // add to the end

$user = ['name' => 'Ali', 'city' => 'Lahore'];
$user['age'] = 30;                      // add a key

foreach ($colors as $i => $color) {
    echo "$i: $color\n";
}
foreach ($user as $key => $value) {
    echo "$key = $value\n";
}
echo count($colors);                    // 3
var_dump(in_array('green', $colors));   // true
var_dump(array_key_exists('city', $user)); // true
arrayforeachbasics