This article covers the topic of how to do the basic work with arrays in PHP. PHP has a powerful support of arrays and brings a lot of functions to work with them. The main functions used to work with array are array() and list(). And this article concentrates mainly on these two functions.
array() function.
It takes a list of element's values and optinally indexes and assigns them to an array. Both string and number indexes can be used in the same array. If index is omitted it is given a value of the biggest index in array + 1 and if index isn't specified in any of elements, it is given a value 0. Here is an example of array() function usage(print_r() function displays the content of an array):
The following code will output:
-
Array
-
(
-
[1] => "Red"
-
[2] => "Green"
-
[3] => "Blue"
-
)
-
Array
-
(
-
[0] => "Zero",
-
[1] => "One",
-
[2] => "Two" ,
-
[3] => "Three",
-
[4] => "Four",
-
[5] => "Five"
-
)
-
Array
-
(
-
["name"] => "John"
-
["surname"] => "Smith"
-
)
To take a value of array's element you can use [ and ] brackets like in the most of other programming languages. The following example shows how to do this:
This code will make the following output:
-
alpha
list() function.
This functions helps with assignment of array elements to variables. It is very often used with functions and simplifies the assignment of returned array to variables. Here is an example of how to use list() function:
Function explode() returns an array of values specified in the second argument(in this case $fullname) and separated by separator specified in the first argument (in this case " "). Than list() function assigns the first value of array returned by explode() function to first variable in list, the second value - to the second cariable and so forth. So this code will output the following result:
Name: John Surname: Smith
Easy, isn't it?
Making sure if an variable is an array. Sometimes you can need to make sure if some variable is an array. Using one variable for storing values of different types (for example: firstly use it to store integer, than to store string and so on) isn't a good idea but you can still need to do that sometimes. That's where is_array() function helps. This function is very easy to use, it needs a specified argument and it returns whether or not it is an array. The following code shows how to work with this function.
The following code will output this to page:
FALSE TRUE
Analogous way. There is an alternate way to check if a variable is an array - gettype() function. Like is_array() it gets one argument. If a specified variable is an array, it returns "array", else it returns another value.
So now you can do the basic stuff with arrays (declaration, values assignment and getting elements). But PHP has much more predefined features to work with arrays but they will be described in future articles.
Yours, Earl Grey
0 Responses
Stay in touch with the conversation, subscribe to the RSS feed for comments on this post.