Array functions in PHP 5

PHP 5 Array Functions – Extremely Useful if Known

Many people have heard about PHP 5, but how much they have applied in their real life is my question.

Today I am here to explain some array functions. These array functions are very much useful and will help you handle arrays very easily :

1 ) array_combine

In many cases we need to get state names from its abbreviation or student names from their roll numbers or registration numbers. For example, think about a database containing student marks and student information. In a table there is student id, registration  and their names, in another there is registration id and marks and in another registration is and examination centre. You may need to sort the array keys or values. Why will you call foreach repeatedly when you can do the same if you combine array keys and values and use multisort for the same?
Suppose you need to combine the region code and region name twice or trice for a form in your custom module in Magento. Why will you call database again and again if you can combine it once and display much faster by array_combine? So here is the example of combining state codes with state names.

<?php 
$abbreviations = array("AL", "AK", "AZ", "AR"); 
$states = array("Alabama", "Alaska", "Arizona", "Arkansas"); 
$combined = array_combine($abbreviations, $states); 
print_r($combined); 
?>

Output:

Array ( [AL] => Alabama [AK] => Alaska [AZ] => Arizona 
[AR] => Arkansas )

 

2) array_walk_recursive

In many open-sources like Magento or in API like Expedia or Viator we have to study the whole set of multidimensional array just to see which keys are fetching what data. We generally, use pre tags before ‘print_r’. What if there is levels within levels. What if you need to get data from each key? By this function you can easily customize the data into a table easily. You can read levels within levels.

<?php
$room_details = array('room_type' => 'Two Bed', 'bathroom' => 'Western with Bath Tub');
$hotel_details = array('room' => $room_details, 'ranking' => 'Three Star');

function print_key_with_levels($item, $key)
{
    echo "$key - $item <br>";
}

array_walk_recursive($hotel_details, 'print_key_with_levels');
?>

 Output:

room_type - Two Bed
bathroom - Western with Bath Tub
ranking - Three Star

 

Subscribe
Notify of
guest
2 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
Jakob Damgaard Møller
Jakob Damgaard Møller
10 years ago

How can:
echo “$key – $item “;
give output like:
room_type is Two Bed

I would expect to see output like:

room_type – Two Bed

Or the echo should be like:
echo “$key is $item “;

But anyways, nice article.

Site
Admin
Reply to  Jakob Damgaard Møller
10 years ago

Thanks Jakob for correcting. Am glad that someone is reading to such minute details. Thanks a lot for your compliments as well. 🙂

2
0
Would love your thoughts, please comment.x
()
x