PHP Simple Arrays

Once you understand PHP Arrays, they really do become simple.

What is an array? In layman’s terms, it’s a way to store multiple items together under one variable. You could create different variables for everything, but sometimes that’s just not practical. Imagine that you’re pulling thousands of records from a database. You can’t, or shouldn’t, create thousands of different variables to store each record. You would use an array and store all of the records under one variable. You could then loop through the array (I know we haven’t covered loops yet) and display each array element.

There are different ways to create PHP arrays. The first way is by assigning array() to a variable. Inside the array() declaration, we’ll put a list of numbers.

 

<?php
$numbers = array(1, 2, 3, 5, 10, 20);
?>

 

Those numbers could serve a purpose, such as represent employee ID’s.

 

<?php
$employee_ids = array(1, 2, 3, 5, 10, 20);
?>

 

Arrays don’t have to store just integer values; they can store any data type including, for example, strings.

 

<?php
$drivers_i_hate = array(
  'Drivers that turn on their signals before checking',
  'Drivers that do the speed limit in the left two lanes',
  'Drivers that are clearly on their phones'
);
?>

 

You’ll notice that each array value is on a separate line. PHP doesn’t have a limit on how many spaces or new line characters you can have after each array element. So, for readability, you can make it look however you want.

How do we access elements inside the array? With the index value. What is an index? It’s just an integer value that’s assigned to each element so that it can be called. In PHP, like most programming languages, we start at index 0 and move up in increments of 1. Why is 0 the first array index? So as not to get too deep into it, I’ll briefly state that it’s because of the way that arrays are stored in memory.

In the $drivers_i_hate array, we have 3 elements; the index values are 0, 1, and 2. To access the first array element, you’ll take your variable, $drivers_i_hate, append a couple of brackets to it, [ ], and place the index value in between the brackets.

 

<?php
echo $drivers_i_hate[0];
// Displays: Drivers that turn on their signals before checking
?>

 

To display the last element, we could just count the number of elements in there, 3, subtract 1, since our index value starts at zero, and place the integer value inside the square brackets.

 

<?php
echo $drivers_i_hate[2];
// Displays: Drivers that are clearly on their phones
?>

 

What if we didn’t know how many elements are in the array? For example, if we were pulling records from a database, and that database table kept getting updated frequently, the number of records would change. Now, what if you wanted to access the last element. You would not be able to hard-code the index value since it changes. We’ll somehow have to count the number of elements in the array and figure out the value that way.

Luckily, PHP has a built-in function calledcount(). There is another function calledsizeof(), which is synonymous to count(). You can choose whichever one you like; I prefer count.

Lets pass the array to the count() function and get the number of elements inside the array. We get 3 since that is the number of elements inside the $drivers_i_hate array.

 

<?php
echo count( $drivers_i_hate );
// Displays: 3
?>

 

With the information that we know so far, let’s see if we can access the last array element. All we have to do is get the number of elements inside the array, subtract 1 from it since the index starts at 0, and place the value in between the square brackets of the array.

 

<?php
// Stores the value 2
$last_index = count($drivers_i_hate) - 1;echo $drivers_i_hate[ $last_index ];
?>

 

If we wanted to, we could just pass the entire expression in between the square brackets; we don’t have to store the index value inside of a variable.

 

<?php
echo $drivers_i_hate[ count($drivers_i_hate) - 1 ];
?>

 

How does PHP evaluate the code above?

  1. PHP sees the echo statement, so it knows that it will be outputting something to the screen.
  2. It arrives at a variable. That variable is an array.
  3. PHP looks inside the square brackets for the index value so that it can figure out which array element it needs to output to the screen.
  4. The index value is not explicitly located inside the square brackets; PHP starts evaluating the expression in an attempt to find out what the index value in there is.
  5. It notices that there is an arithmetic operation: the left side minus the right side.
  6. PHP looks for a number on the left side. It doesn’t see one, but it does see the count function.
  7. It evaluates the count() function and gets the value 3.
  8. It then subtracts 1 from 3 and gets the value 2. The integer value 2 is the index value.
  9. It seeks the memory location that was allocated for that index value and retrieves the string:Drivers that are clearly on their phones.
  10. PHP displays that string onto the screen.

There is another way to initialize arrays; instead of using the array() declaration, we could simply use the square bracket notation.The square bracket notation was introduced in PHP 5.4.I personally prefer the square bracket notation for initializing arrays.

 

<?php
// Set $people to empty array
$people = [];
?>

 

Arrays in PHP are not required to store only 1 data type. This is actually one of my favorite features of PHP. I want to be able to mix and match data types every once in a while. In other programming languages, like Java, you cannot do this.

We’ll create an array, called $person, and we’ll store strings, integers, floating point numbers, and even boolean values. Let’s use the square bracket notation this time to initialize the array.

 

<?php
$person = [
  'Dino Cajic',
  32,
  '111-11-1111', // Don't store SSN like this
  'dinocajic@gmail.com',
  42.5, // favorite decimal
  true // is awesome
];
?>

 

If we wanted to see all of the values inside the array as well as the data type of each value, we could use PHP’s built invar_dump()function. The var_dump() function literally just dumps information about a variable.

 

<?php
var_dump($person);
?>

 

 

What if we wanted to add a new element to the array after the array has been initialized. There are a couple of approaches that you can take. We can add an array element to the end of the array by using the array name, append the square brackets to the end of the name, insert the last index value + 1 inside the brackets, and finally assign the value to it.

We’ll store the occupation of the person inside of our $person array under index 6. Why 6, because indices 0 through 5 are already taken.

 

<?php
$person[6] = "Author";
?>

 

If you want to place the value inside the array without worrying about what is the last array element, you can simply use open/close brackets. PHP will automatically assign the element to the last index value in the array.

 

<?php
// Book title stored in index 7
$person[] = "An Illustrative Introduction to Algorithms";
?>

 

You also don’t have to go in numerical order when assigning an element to the array. The $person array is currently using indices 0 through 7. We could use array index 26 as our next element location and it will assign it to that index. Elements 8 through 25 will not exist.

 

<?php
$person[26] = "https://medium.com/@dinocajic";
?>

 

 

If we pass the $person array to the count function, the size of this array will be 9. This means that we can’t use the trick that we used before to get the last element of the array. We would proceed, like before, to subtract 1 from 9, and our index value would be 8. Unfortunately, we need 26. I suggest that unless you have a good reason to create custom index values, that you don’t arbitrarily assign index values like we just did.

How do we modify existing elements? First, we have to know the element’s index value. We then assign a new value to that index.

 

<?php
// To modify the age from 32 to 33
// New value for element at index 1 is 33
$person[1] = 33;
?>

To remove an array element, we’ll use the built-in unset() function. We’ll pass the array element to it and it will remove it from the array. If we wanted to remove the last element that we just added, element at index 26, and reinsert it as the last element in the array, we can, but we get some unexpected results.

 

<?php
// Removes array element 26 from the array
unset( $person[26] );// What array index will the link be added to?
$person[] = "https://medium.com/@dinocajic";
?>

 

Before we reinsert the string, https://medium.com/@dinocajic, into the $person array, we can verify that the last element inside the array is located at index 7. After we insert it, the link will be at index 27. It turns out that PHP remembers the location of the last index value even after its been removed.

 

 

PHP Tutorial Series

Continue your learning with these articles

PHP Strings

What do you use your Strings for?

PHP – P8: Strings

A string is just a sequence of characters surrounded by quotes; strings in PHP are placed inside either single or double quotes. In other programming languages, like Java, strings are surrounded by double quotes and individual characters are surrounded by single quotes.

PHP Simple Arrays

Once you understand them, they really do become simple.

PHP — P9: SIMPLE ARRAYS

What is an array? In layman’s terms, it’s a way to store multiple items together under one variable. You could create different variables for everything, but sometimes that’s just not practical.

PHP Associative Arrays

I’D LIKE YOU TO MEET MY ASSOCIATE.

PHP – P10: ASSOCIATIVE ARRAYS

If you’re familiar with other programming languages, an associative array is pretty much a dictionary. Instead of accessing the array by using an index value, you’ll access it by using a key.

Leave a Reply