Some Important Array Functions

The following table shows some of the more common array manipulation functions.

Useful Array Functions
FunctionExplanation
sort()Sorts an array alphabetically. Elements will be assigned to new index numbers.
asort()Sorts associative arrays alphabetically by value. The index association remains intact.
ksort()Sorts associative arrays alphabetically by key. The index association remains intact.
rsort()Reverse sorts an array alphabetically. Elements will be assigned to new index numbers.
arsort()Reverse sorts associative arrays alphabetically by value. The index association remains intact.
krsort()Reverse sorts associative arrays alphabetically by key. The index association remains intact.
shuffle()Randomly sorts the array. For the order to be sorted differently each time, the random number generator needs to be seeded with rsand().
array_reverse()Returns an array with the elements in reverse order.
array_walk()Applies a user function to every element of an array.
count()Returns the number of elements in an array.
explode()Converts a string to an array by splitting it on a specified separator.
is_array()Takes one parameter and returns true or false depending on whether the parameter passed is an array.
array_keys()Returns all the keys of an associative array as an array.
array_key_exists()Checks to see if a specified key exists in an array.

Creating an array and initialize it with the same values

The PHP array_pad() function allows you to create and array with values initialized to the same content. The array_pad() function takes three arguments. The first arguments are the array itself, the next arguments are a number indicating the padding size and the last argument is the value that will be used to pad or initialize the array content.

The array_pad() function doesn’t modify the original array during the padding process. If you want to have the padded result back to the original array you have to assign the result of the array_pad() function to the original array.

Another thing that you need to know is that if give the second argument to the array_pad function is a positive value the pad will be added at the end of the array. But if you give a negative value for the second argument the array will be padded at the start of the array.

Let’s take a look at some code snippet below:

<?php
//
// Creates an array with 5 elements and initialize each element
// with 0
//
$numbers = array_pad(array(), 5, 0);
echo "Numbers: ";
print_r(implode(', ', $numbers));
echo "\n";

//
// First we create a vowels array with some values. Next we create
// another array by padding the vowels array to make it to be 10 in
// length and pad it with an empty string.
//
$vowels = array('a', 'i', 'u', 'e', 'o');
$padded = array_pad($vowels, 10, '');
echo "Vowels : ";
print_r(implode(', ', $padded));
echo "\n";

//
// Assign the value back the the $vowel original array.
//
$vowels = array_pad($vowels, 10, '');
echo "Vowels : ";
print_r(implode(', ', $vowels));
echo "\n";

//
// Using a negative value to add padding at the start of the array.
//
$random = array(3, 5, 1, 2, 9);
$randomPadded = array_pad($random, -10, 0);
echo "Numbers: ";
print_r(implode(', ', $randomPadded));

?>  

And here is the result of the code snippet:

Numbers: 0, 0, 0, 0, 0
Vowels : a, i, u, e, o, , , , ,
Vowels : a, i, u, e, o, , , , ,
Numbers: 0, 0, 0, 0, 0, 3, 5, 1, 2, 9

Creating an array with a range of values

In this code snippet example, you will learn how to create an array and assign a range of values into the array. To do this in PHP you can use the range() function. The range() function creates an array of consecutive integer or character values between the two values passed as the arguments to this function.

Here is the code snippet:

<?php
//
// Creates a range of integers from 1 to 10
//
$numbers = range(1, 10);
echo "Numbers: ";
print_r(implode(', ', $numbers));
echo "\n";

//
// Creates a lowercase characters sequence from a to z
//
$lowercaseChars = range('a', 'z');
echo "Lowercase: ";
print_r(implode(', ', $lowercaseChars));
echo "\n";

//
// Creates a uppercase characters sequence from A to Z
//
$uppercaseChars = range('A', 'Z');
echo "Uppercase: ";
print_r(implode(', ', $uppercaseChars));
echo "\n";

//
// Creates a range of reversed integers from 10 to 1
//
$reverseNumbers = range(10, 1);
echo "Reverse Numbers: ";
print_r(implode(', ', $reverseNumbers));
echo "\n";  

Executing this code snippet will give you the following result:

Numbers: 1, 2, 3, 4, 5, 6, 7, 8, 9, 10
Lowercase: a, b, c, d, e, f, g, h, i, j, k, l, m, n, o, p, q, r, s, t, u, v, w, x, y, z
Uppercase: A, B, C, D, E, F, G, H, I, J, K, L, M, N, O, P, Q, R, S, T, U, V, W, X, Y, Z
Reverse Numbers: 10, 9, 8, 7, 6, 5, 4, 3, 2, 1

Removing some elements from array

To remove some element from an array we can use the array_splice() function. This function will take arguments such as the input array, the offset and the length. This function will return the extracted elements from the input array. And the input array will be modified to not contain the removed elements.

There are some rules to remember regarding the offset and the length parameter.

  • When the offset is defined and have a positive value it will start from the beginning of the array.
  • When the offset have a negative value it will start from the end of the array.
  • When the length is defined and have a positive value it will have that many elements in the sequence.
  • When the length have a negative value it will stop that many elements from the end of the array.

Let see the code snippet below:

<?php
$fruits = array('orange', 'apple', 'banana', 'mango', 'grape', 'lemon');
//
// Remove banana, mango, grape and lemon from the $fruits.
//
$result = array_splice($fruits, 2);
print 'Fruits: ' . implode(', ', $fruits) . "\n";
print 'Result: ' . implode(', ', $result) . "\n";

$fruits = array('orange', 'apple', 'banana', 'mango', 'grape', 'lemon');
//
// Remove banana and mango the $fruits.
//
$result = array_splice($fruits, 2, 2);
print 'Fruits: ' . implode(', ', $fruits) . "\n";
print 'Result: ' . implode(', ', $result) . "\n";

$fruits = array('orange', 'apple', 'banana', 'mango', 'grape', 'lemon');
//
// Remove apple, banana, mango and grape from the $fruits.
//
$result = array_splice($fruits, 1, -1);
print 'Fruits: ' . implode(', ', $fruits) . "\n";
print 'Result: ' . implode(', ', $result) . "\n"; 

The result of the snippet:

Fruits: orange, apple
Result: banana, mango, grape, lemon

Fruits: orange, apple, grape, lemon
Result: banana, mango

Fruits: orange, lemon
Result: apple, banana, mango, grape

Eliminate duplicate elements in array

You want to eliminate duplicate elements from an array to create an array with a unique value. To do this you can use the array_unique() function. This function takes in the array as an argument and will return you a new array with unique elements in it. Let see the snippet below:

Printing out the contents of an array variable

The are many ways available to print out the contents or elements of an array variable. You can print the contents out using a loop statement like forforeach or while loop. You can also join the array elements into a single string separated by commas using the implode() function as an alternative way doing it.

Let see the snippet below:

<?php
$myArray = array('a', 'b', 'c', 'd', 'e');

// Print out using for loop.
for ($i = 0; $i < count($myArray); $i++) {
echo $myArray[$i];
}

echo "\n";

// Print out using foreach loop.
foreach (array_keys($myArray) as $key) {
echo $myArray[$key];
}

echo "\n";

// Print out using while loop.
$index = 0;
while ($index < count($myArray)) {
echo $myArray[$index];
$index++;
}

echo "\n";

// Print out using implode(), convert array into string
// separated each element using comma.
$str = implode(', ', $myArray);
echo $str;  

The are also other functions that you can use the print the contents of an array, or even an array of arrays. These functions can help you a lot when debugging your code. The function that we talked here is the print_r() and var_dump() function.

Let see some examples below:

// Declares an array of arrays and print the elements using
// print_r() function.
$matrix = array(
array(1, 2, 3),
array(2, 3, 1),
array(3, 1, 2)
);
print_r($matrix);

// Declare an associative array of user and print out using
// var_dump() function.
$user = array(
‘username’ => ‘admin’,
‘password’ => ‘s3cr3t’,
‘fullName’ => ‘Foo Bar’,
‘address’ => array(
‘street’ => ‘Sunset Road’,
‘city’ => ‘Kuta’,
‘zipcode’ => ‘90000’
)
);
var_dump($user);

The result of print_r() followed by var_dump().

How to check if a variable is an array

To check if a variable is an array we can use the is_array() function. This function takes a variable to be evaluated as the parameter. If the variable is an array this function will return a boolean true otherwise it will return false.

Let’s see the code snippet below:

 <?php
$array = array(
"color" => "blue",
"size" => 8.5,
"price" => 100
);

//
// Finds whether $array is an array.
//
if (is_array($array)) {
echo "\$array is an array.";
} else {
echo "\$array is not an array.";
}  

Getting the keys of an array

In this example, you will learn how to get the keys of an array variable. To get the keys you can use the array_keys() function and pass the array variable as parameter. This function will return an array that contains all the keys of the array.

In the code snippet below, we declare an array with some elements. We use the array_keys() to get the keys of the array and print it using the print_r() function to make it easily readable. And then we use a for loop to iterate the array and read the value using the array key.

<?php
$array = array (
"one" => 1,
"two" => 2,
"three" => 3,
"four" => 4,
"student" => array("name" => "Alice", "age" => 15)
);

//
// Print keys for of the array.
//
$keys = array_keys($array);
print_r($keys);

//
// Get the value from the array using the keys
//
echo "Print array contents:\n";
for ($i = 0; $i < count($keys); $i++) {
if (is_array($array[$keys[$i]])) {
print_r($array[$keys[$i]]);
} else {
echo $keys[$i] . " = > " . $array[$keys[$i]] . "\n";
}
}   

The result of the code snippet are:

Reversing elements of an array

The code snippet below shows you how to reverse the order of the elements of an array. We can use the function array_reverse() to reverse array’s elements. This function takes an array to be reversed as parameter and return the reversed version of the array.

Let’s see the code snippet below:

 <?php
//
// An array of letters
//
$letters = array("a", "b", "c", "d", "e", "f", "g", "h", "i", "j");

//
// Reverse the order of the array elements.
//
$reverse = array_reverse($letters);

echo "Original: " . implode(",", $letters) . "\n";
echo "Reverse : " . implode(",", $reverse); 

And here is the result of our code:

a,b,c,d,e,f,g,h,i,j
j,i,h,g,f,e,d,c,b,a

Add a Comment

Your email address will not be published. Required fields are marked *

ABOUT CODINGACE

My name is Nohman Habib and I am a web developer with over 10 years of experience, programming in Joomla, Wordpress, WHMCS, vTiger and Hybrid Apps. My plan to start codingace.com is to share my experience and expertise with others. Here my basic area of focus is to post tutorials primarily on Joomla development, HTML5, CSS3 and PHP.

Nohman Habib

CEO: codingace.com

Request a Quote