PHP Array tutorial - Array functions


Home - Tutorials - Basics

In this tutorial I will show you how to work with arrays in PHP. You will learn how to create, sort or print an array. Besides this we will touch on multidimensional arrays as well.

Tutorial info:


Name:PHP Array tutorial
Total steps:7
Category:Basics
Level:Beginner

Bookmark PHP Array tutorial



Bookmark and Share

Step 6 - Array functions


PHP Array tutorial


During programming it can be neccessary to manipulate arrays. Do do this PHP has some usefull built in functions.

Get the length of the array, or with other words how many elements are in the array. To get this information you can use the sizeof function. It tells you how big is the actual data. You can use it like this:

Code:
  1. echo sizeof($colorList);

Sometimes you want to remove an element from the array. In this case you can use the unset function like this:
Code:
  1. unset($colorList["sky"]);
To check whether an array has a requested element you can use the isset function as follows:
Code:
  1. if (isset($colorList["grass"])) echo "OK";
And last you sometimes want to sort your array for eaxmple to display its content in alphabetical order. To do this you have more possibilities. There are more built in array sorting functions in PHP. The most known are sort and asort. The difference between them is that sort renumbers the keys so you will lost the key values. So if you need the key names (associative arrays) use the asort function.
You can use them as follows:
Code:
  1. asort($colorList);
  2. sort($colorList);
Both of the functions sorts values in ascending order. If you want to sort them descending use the corresponding rsort and arsort functions.

On the last page you will find a complete example code which demonstrates array handling.





Previous Step of PHP Array tutorialNext Step of PHP Array tutorial


Tags: array, php array, sort array, create array, print array, array length



Follow phpf1 on Twitter




F1 Site Family
AJAX F1
HTML F1
Java F1
JavaScript F1
PHP F1

Total time: 0.0268