Archive for the 'php tutorials' Category

Working with arrays in PHP (part ii)

Sunday, September 10th, 2006

This article is the second part of articles series on arrays usage in PHP. It covers usage of predefined sorting, searching and filtering functions. There are plenty of functions for sorting, searching and filtering arrays in PHP. This article will help you with choosing the appropriate function to use in a given problem.

Using sort(), asort(), arsort(), rsort(), ksort() functions.
All these functions take two parameters, the second one is optional. They are used for sorting the array elements. The first parameter is the array to be sorted. The second parameter can take three values:
SORT_REGULAR (compare items normally),
SORT_NUMERIC (compare items numerically),
SORT_STRING (compare items as strings).
sort() function sorts specified array by its elements according to the sorting type specified.
rsort() acts like sort() but it does sorting in reverse order.
asort() function sorts the specified array by elements values and changes their order but it doesn't reassign values with indexes, it is mostly important for arrays with string indexes.
arsort() is similar to asort() except that it sorts the array in reverse order.
Here is an example that shows differences between all these sorting functions:

PHP:
  1. $a = array("red","green","blue");
  2. print "Initial content: "; print_r($a);
  3. sort($a);
  4. print "Sorted with sort(): "; print_r($a);
  5. rsort($a);
  6. print "Sorted with rsort(): "; print_r($a);
  7. asort($a);
  8. print "Sorted with asort(): "; print_r($a);
  9. arsort($a);
  10. print "Sorted with arsort(): "; print_r($a);

The output will be the following:

CODE:
  1. Initial content: Array ( [0] => red [1] => green [2] => blue )
  2. Sorted with sort(): Array ( [0] => blue [1] => green [2] => red )
  3. Sorted with rsort(): Array ( [0] => red [1] => green [2] => blue )
  4. Sorted with asort(): Array ( [2] => blue [1] => green [0] => red )
  5. Sorted with arsort(): Array ( [0] => red [1] => green [2] => blue )

As you can see, asort() and arsort() functions don't change indexes but change the actual items order.

ksort() and krsort() functions.
These functions are very similar with the above except one detail. They sort an array by its keys values, instead of elements values. This is maily useful for string-indexed arrays. Here is an example code what can explain how this works:

PHP:
  1. $a = array("d"=>"Four","a"=>"One","c"=>"Three","b"=>"Two");
  2. ksort($a);
  3. print "Sorted with ksort(): "; print_r($a);
  4. krsort($a);
  5. print "Sorted with krsort(): "; print_r($a);

As you can see array items are sorted by keys and not by values:

CODE:
  1. Sorted with ksort(): Array ( [a] => One => Two [c] => Three [d] => Four )
  2. Sorted with krsort(): Array ( [d] => Four [c] => Three [b] => Two [a] => One )

Using "natural sorting".
"Natural sorting" means sorting more close to human than traditional computer sorting algorithms. PHP offeres two functions for natural sorting: natsort() and natcasesort() where the first is case-sensitive and the second case-insensitive. To understand how "natural sorting" works look at the following example:

PHP:
  1. $a = array("image1.png","imag10.png","image2.png","image20.png");
  2. natsort($a);
  3. print_r($a);

This will give the following output:

CODE:
  1. Array ( [0] => image1.png [2] => image2.png [1] => image10.png [3] => image20.png )

This result is unlike the traditional algorithm what will give result like following: (image1, image10, image2, image20).

Searching for items in array.
PHP has two functions for searching items in arrays. They are: in_array() and array_search(). They both search for a needle(first argument) in haystack(second argument). They both take two arguments; the first is the element to be found and the last is optional and means the strictness of search. If it is set to TRUE it checks not only needle and haystack's elements equality but also that they both are the same type. If found, in_array() returns TRUE, else it returns FALSE. The array_search() returns the index of seeking value in specified array. Here is an example of these functions usage:

PHP:
  1. $a = array(1,2,3,4,5);
  2. if(in_array(5,$a)) print "Found on index: ".array_search(5,$a);
  3. else print "Not found";

It will output:

CODE:
  1. Found on index 4

Filtering array.
PHP has a filter() function that allows to filter an array with an own callback function. It takes two arguments: array and callback function. The function returns the filtered array. Here is the code that shows this:

PHP:
  1. function cms_ood($value)
  2. {
  3. return ($value%2!=1);
  4. }
  5. function cms_even($value)
  6. {
  7. return ($value%2!=0)
  8. }
  9. $a = array(1,2,3,4,5);
  10. $filtered_odd=array_filter($a,"filter_odd");
  11. print "Filtered odd: "; print_r($filtered_odd);
  12. print "Filtered even: "; $filtered_even=array_filter($a,"filter_even");

Here is the result of the script:

CODE:
  1. Filtered odd: Array ( [1] => 2 [3] => 4 )
  2. Filtered even: Array ( [0] => 1 [2] => 3 [4] => 5 )

Now you know most of PHP's array sorting, searching and filtering features and can decide what function would be better for your task.

Working with arrays in PHP (part i)

Sunday, September 10th, 2006

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):

PHP:
  1. $colors=array(1=>'Red','Green',Blue);
  2. $numbers=array('Zero','One','Two','Three','Four','Five');
  3. $profile=array('name'=>'John','surname'=>'Smith');
  4. print "Colors: ";
  5. print_r($colors);
  6. print "Numbers: ";
  7. print_r($numbers);
  8. print "Profile: ";
  9. print_r($profile);
  10. ?>

The following code will output:

CODE:
  1. Array
  2. (
  3. [1] => "Red"
  4. [2] => "Green"
  5. [3] => "Blue"
  6. )
  7. Array
  8. (
  9. [0] => "Zero",
  10. [1] => "One",
  11. [2] => "Two" ,
  12. [3] => "Three",
  13. [4] => "Four",
  14. [5] => "Five"
  15. )
  16. Array
  17. (
  18. ["name"] => "John"
  19. ["surname"] => "Smith"
  20. )

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:

PHP:
  1. $letters=array("alpha","betha","gamma","delta");
  2. print $letters[0];
  3. ?>

This code will make the following output:

CODE:
  1. 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:

PHP:
  1. $fullname="John Smith";
  2. list($name,$surname)=explode(" ",$fullname);
  3. print "Name: $name Surname: $surname";
  4. ?>

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.

PHP:
  1. $fullname="John Smith";
  2. $personal_info=array('name'=>"John",'surname'=>"Smith");
  3. print is_array($fullname)." ".is_array($personal_info);
  4. ?>

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