Logo
Unit 7 – PHP Arrays

PHP Arrays

Duration: 5 minutes

Hello, intrepid PHP explorer!

Arrays are one of the fundamental data structures in programming, and PHP offers a versatile approach to them. An array is used to store multiple values in a single variable.

This makes managing related data points simpler and more efficient.

In this module, we’ll dive deep into the essentials of arrays in PHP: how to create them, access their elements, and modify them. So, gear up as we embark on another enlightening PHP module!

Basics of Arrays

Creating Arrays

There are primarily three types of arrays in PHP:

  • Indexed arrays - Arrays with numeric indexes.
  • Associative arrays - Arrays with named keys.
  • Multidimensional arrays - Arrays containing other arrays.

Here’s how to create them:

// Indexed array
$colors = array("Red", "Green", "Blue");
// Associative array
$person = array("firstName" => "Zahwah", "lastName" => "Jameel");
// Multidimensional array
$matrix = array(
array(1, 2),
array(3, 4)
);

Accessing Arrays

To access the elements of an array, you’d use the array name followed by the index or key in square brackets:

echo $colors[1]; // Outputs: Green
echo $person["firstName"]; // Outputs: Zahwah

Modifying Arrays

To modify an existing array, you can directly assign a value to one of its keys or indices:

$colors[1] = "Yellow"; // Changes the value at index 1 to Yellow
$person["firstName"] = "Sarah"; // Changes the value of the key "firstName" to Sarah

Additionally, PHP offers a myriad of functions to manipulate arrays, like array_push, array_pop, array_shift, and many more.

Exercise

It’s hands-on time!

  • Create an indexed array of your favorite fruits.
  • Add a new fruit to the end of the array.
  • Access and display the first fruit in the array.
  • Modify the second fruit in the array to another fruit of your choice.

Conclusion

Well done on navigating the vast landscape of arrays in PHP! Mastering arrays is crucial, as they form the backbone of many operations and algorithms in programming. With this knowledge, you are even better equipped to tackle more complex PHP tasks.

Keep up the enthusiasm and let’s continue to explore further!

Next Tutorial: Associative Arrays

5 minutes Minutes

Continue

Code on the Go with our Mobile App!

Unleash your coding potential anytime, anywhere!

Download Now!