DEV Community

ahmed SENEINA
ahmed SENEINA

Posted on • Originally published at gogokodo.com

PHP arrays: indexed, associative and foreach without confusion

Most PHP beginners do not struggle because arrays are hard.

They struggle because three ideas arrive at the same time:

  • indexed arrays
  • associative arrays
  • foreach

Indexed array:

$languages = ["PHP", "JavaScript", "Python"];
echo $languages[0];
Enter fullscreen mode Exit fullscreen mode

Associative array:

$user = [
    "name" => "Nadia",
    "role" => "developer"
];

echo $user["name"];
Enter fullscreen mode Exit fullscreen mode

Foreach with values:

foreach ($languages as $language) {
    echo $language;
}
Enter fullscreen mode Exit fullscreen mode

Foreach with keys and values:

foreach ($user as $key => $value) {
    echo $key . ": " . $value;
}
Enter fullscreen mode Exit fullscreen mode

The key idea: => links a key to a value.

I published a full French beginner guide with examples, common mistakes, nested arrays and safe HTML output:

https://gogokodo.com/tableaux-php-array-fonctions-guide-complet

Top comments (0)