w1coding.comAll tutorials

PHP Arrays

PHP lessons
  1. Environment Setup
  2. Introduction
  3. Variables
  4. Basics
  5. Operators
  6. Control
  7. Loops
  8. Variables
  9. Functions
  10. Arrays
  11. Superglobal
  12. File
  13. Loops
  14. Date
  15. Loops
  16. Strings
  17. Error
  18. Class
  19. File
  20. Include
  21. Sessions
  22. Mysql
  23. Cookies
  24. Forms
  25. Cookies
  26. Regular
  27. Authenthication
  28. Fileupload
  29. Mvc
  30. Responsive

Arrays in PHP

Arrays in PHP are used to store multiple values in a single variable. PHP supports both indexed arrays and associative arrays.

Indexed Arrays

An indexed array stores values with a numeric index:

      
        <?php
          $fruits = array("Apple", "Banana", "Cherry");
          echo $fruits[0]; // Outputs Apple
        ?>
      
    

Associative Arrays

Associative arrays use named keys to store values:

      
        <?php
          $person = array("name" => "John", "age" => 30);
          echo $person["name"]; // Outputs John
        ?>
      
    

Activity

Try It Yourself!

Create an associative array for a car with keys for "make", "model", and "year". Output the value of the "model" key.

Quiz

Quick Quiz

  1. What is the difference between an indexed array and an associative array?
  2. How do you access the value of an associative array?

Answers: Indexed arrays use numeric indexes, while associative arrays use named keys. Access values in associative arrays using the key (e.g., $array["key"]).