w3resource

PHP arrays - Exercises, Practice, Solution


This resource offers a total of 295 PHP arrays problems for practice. It includes 59 main exercises, each accompanied by solutions, detailed explanations, and four related problems.

[An Editor is available at the bottom of the page to write and execute the scripts.]

1. Colorful Memory String

$color = array('white', 'green', 'red', 'blue', 'black');
Write a script which will display the following string -
"The memory of that scene for me is like a frame of film forever frozen at that moment: the red carpet, the green lawn, the white house, the leaden sky. The new president and his first lady. - Richard M. Nixon"
and the words 'red', 'green' and 'white' will come from $color.

Click me to see the solution

2. Display Colors in Specific Format

$color = array('white', 'green', 'red'')
Write a PHP script which will display the colors in the following way :
Output :
white, green, red,

  • green
  • red
  • white

Click me to see the solution

3. Sorted Capitals from CEU Array

$ceu = array( "Italy"=>"Rome", "Luxembourg"=>"Luxembourg", "Belgium"=> "Brussels", "Denmark"=>"Copenhagen", "Finland"=>"Helsinki", "France" => "Paris", "Slovakia"=>"Bratislava", "Slovenia"=>"Ljubljana", "Germany" => "Berlin", "Greece" => "Athens", "Ireland"=>"Dublin", "Netherlands"=>"Amsterdam", "Portugal"=>"Lisbon", "Spain"=>"Madrid", "Sweden"=>"Stockholm", "United Kingdom"=>"London", "Cyprus"=>"Nicosia", "Lithuania"=>"Vilnius", "Czech Republic"=>"Prague", "Estonia"=>"Tallin", "Hungary"=>"Budapest", "Latvia"=>"Riga", "Malta"=>"Valetta", "Austria" => "Vienna", "Poland"=>"Warsaw") ;

Create a PHP script which displays the capital and country name from the above array $ceu. Sort the list by the capital of the country.

Sample Output :
The capital of Netherlands is Amsterdam 
The capital of Greece is Athens 
The capital of Germany is Berlin 
- - - - - - - - - - - - - - - - - - - - - - - - -
- - - - - - - - - - - - - - - - - - - - - - - - -

Click me to see the solution

4. Delete Element & Normalize Keys

$x = array(1, 2, 3, 4, 5);
Delete an element from the above PHP array. After deleting the element, integer keys must be normalized.
Sample Output :
array(5) { [0]=> int(1) [1]=> int(2) [2]=> int(3) [3]=> int(4) [4]=> int(5) } 
array(4) { [0]=> int(1) [1]=> int(2) [2]=> int(3) [3]=> int(5) }

Click me to see the solution

5. Get First Element from Associative Array

$color = array(4 => 'white', 6 => 'green', 11=> 'red');
Write a PHP script to get the first element of the above array.
Expected result : white

Click me to see the solution

6. Decode JSON String

Write a PHP script which decodes the following JSON string.
Sample JSON code :
{"Title": "The Cuckoos Calling",
"Author": "Robert Galbraith",
"Detail": {
"Publisher": "Little Brown"
}}
Expected Output :
Title : The Cuckoos Calling
Author : Robert Galbraith
Publisher : Little Brown

Click me to see the solution

7. Insert New Array Item by Position

Write a PHP script that inserts a new item in an array in any position.
Expected Output :
Original array : 
1 2 3 4 5 
After inserting '$' the array is :
1 2 3 $ 4 5

Click me to see the solution

8. Sort Associative Array by Key and Value

Write a PHP script to sort the following associative array :
array("Sophia"=>"31","Jacob"=>"41","William"=>"39","Ramesh"=>"40") in
a) ascending order sort by value
b) ascending order sort by Key
c) descending order sorting by Value
d) descending order sorting by Key

Click me to see the solution

9. Average Temperature & Extremes

Write a PHP script to calculate and display average temperature, five lowest and highest temperatures.
Recorded temperatures : 78, 60, 62, 68, 71, 68, 73, 85, 66, 64, 76, 63, 75, 76, 73, 68, 62, 73, 72, 65, 74, 62, 62, 65, 64, 68, 73, 75, 79, 73
Expected Output :
Average Temperature is : 70.6 
List of seven lowest temperatures : 60, 62, 63, 63, 64, 
List of seven highest temperatures : 76, 78, 79, 81, 85,

Click me to see the solution

10. Bead-Sort Algorithm for Array Sorting

Write a PHP program to sort an array of positive integers using the Bead-Sort Algorithm.
According to Wikipedia "Bead-sort is a natural sorting algorithm, developed by Joshua J. Arulanandham, Cristian S. Calude and Michael J. Dinneen in 2002. Both digital and analog hardware implementations of bead sort can achieve a sorting time of O(n); however, the implementation of this algorithm tends to be significantly slower in software and can only be used to sort lists of positive integers".

Input array : Array ( [0] => 5 [1] => 3 [2] => 1 [3] => 3 [4] => 8 [5] => 7 [6] => 4 [7] => 1 [8] => 1 [9] => 3 )
Expected Result : Array ( [0] => 8 [1] => 7 [2] => 5 [3] => 4 [4] => 3 [5] => 3 [6] => 3 [7] => 1 [8] => 1 [9] => 1 )

Click me to see the solution

11. Merge Arrays by Index

Write a PHP program to merge (by index) the following two arrays.
Sample arrays :
$array1 = array(array(77, 87), array(23, 45));
$array2 = array("w3resource", "com");
Expected Output :

Array  
(      
[0] => Array          
(              
[0] => w3resource              
[1] => 77              
[2] => 87          
)        
[1] => Array          
(              
[0] => com              
[1] => 23              
[2] => 45          
)    
)

Click me to see the solution

12. Change Array Values to Lower and Upper Case

Write a PHP function to change the following array's all values to upper or lower case.
Sample arrays :
$Color = array('A' => 'Blue', 'B' => 'Green', 'c' => 'Red');
Expected Output :
Values are in lower case.
Array ( [A] => blue [B] => green [c] => red ) 
Values are in upper case.
Array ( [A] => BLUE [B] => GREEN [c] => RED )

Click me to see the solution

13. Display Numbers Divisible by 4 Without Control Statements

Write a PHP script which displays all the numbers between 200 and 250 that are divisible by 4.
Note : Do not use any PHP control statement.
Expected Output : 200,204,208,212,216,220,224,228,232,236,240,244,248

Click me to see the solution

14. Get Shortest and Longest String Length from Array

Write a PHP script to get the shortest/longest string length from an array.
Sample arrays : ("abcd","abc","de","hjjj","g","wer")
Expected Output : The shortest array length is 1. The longest array length is 4.

Click me to see the solution

15. Generate Unique Random Numbers within a Range

Write a PHP script to generate unique random numbers within a range.
Sample Range : (11, 20)
Sample Output : 17 16 13 20 14 19 18 15 11 12

Click me to see the solution

16. Get the Largest Key in an Array

Write a PHP script to get the largest key in an array.
Click me to see the solution

17. Lowest Non-zero Integer Function

Write a PHP function that returns the lowest integer that is not 0.
Click me to see the solution

18. Floor Decimal with Precision

Write a PHP function to floor decimal numbers with precision.
Note: Accept three parameters number, precision, and $separator
Sample Data :
1.155, 2, "."
100.25781, 4, "."
-2.9636, 3, "."

Expected Output
:
1.15
100.2578
-2.964

Click me to see the solution

19. Print Specific Elements from Multidimensional Array

Write a PHP script to print "second" and Red from the following array.
Sample Data :
$color = array ( "color" => array ( "a" => "Red", "b" => "Green", "c" => "White"),
"numbers" => array ( 1, 2, 3, 4, 5, 6 ),
"holes" => array ( "First", 5 => "Second", "Third"));

Click me to see the solution

20. Sort Array by Priority List

Write a PHP function to sort an array according to another array acting as a priority list.
Click me to see the solution

21. Sort Subnets

Write a PHP function to sort subnets.
Click me to see the solution

22. Sort Array by Day and Username

Write a PHP script to sort the following array by the day (page_id) and username.
Click me to see the solution

23. Sort Multi-Dimensional Array by Specific Key

Write a PHP program to sort a multi-dimensional array set by a specific key.
Click me to see the solution

24. Case-Insensitive Natural Order Sorting

Write a PHP script to sort an array using case-insensitive natural ordering.
Click me to see the solution

25. Sort Entity Letters

Write a PHP function to sort entity letters.
Click me to see the solution

26. Shuffle Associative Array Preserving Keys

Write a PHP function to shuffle an associative array, preserving key, value pairs.
Click me to see the solution

27. Generate Random Password Using Shuffle

Write a PHP function to generate a random password (contains uppercase, lowercase, numeric and other) using shuffle() function.
Click me to see the solution

28. Reverse Sort Array

Write a PHP script to sort an array in reverse order (highest to lowest).

Click me to see the solution

29. Array Range from String

Write a PHP program to generate an array with a range taken from a string.
Click me to see the solution

30. Create Letter Range with Arbitrary Length

Write a PHP program to create a letter range with arbitrary length.
Click me to see the solution

31. Get Index of Highest Value in Associative Array

Write a PHP program to get the index of the highest value in an associative array.
Click me to see the solution

32. Get File Extension

Write a PHP program to get the extension of a file.
Click me to see the solution

33. Search Value Within Associative Array

Write a PHP function to search a specified value within the values of an associative array.
Click me to see the solution

34. Sort Associative Array (Case-Sensitive by Values)

Write a PHP program to sort an associative array (alphanumeric with case-sensitive data) by values.
Click me to see the solution

35. Trim All Array Elements Using array_walk

Write a PHP script to trim all the elements in an array using array_walk function.
Click me to see the solution

36. Convert Array Elements to Lower and Upper Case

Write a PHP script to lower-case and upper-case, all elements in an array.
Click me to see the solution

37. Count Occurrences of a Specific Value in Array

Write a PHP script to count the total number of times a specific value appears in an array.
Click me to see the solution

38. Multidimensional Unique Array by Key Index

Write a PHP function to create a multidimensional unique array for any single key index.
Click me to see the solution

39. Remove Duplicate Values from Array

Write a PHP program to remove duplicate values from an array which contains only strings or only integers.
Click me to see the solution

40. Sorted Array Without Preserving Keys

Write a PHP program to get a sorted array without preserving the keys.
Click me to see the solution

41. Identify Non-Unique Email Addresses

Write a PHP program to identify the email addresses which are not unique.
Click me to see the solution

42. Unique Flattened Values from Multidimensional Arrays

Write a PHP function to find unique values from multidimensional arrays and flatten them in zero depth.
Click me to see the solution

43. Merge Two Comma-Separated Lists with Unique Values

Write a PHP script to merge two commas separated lists with unique value only.
Click me to see the solution

44. Remove Specified Duplicate Entry from Array

Write a PHP a function to remove a specified, duplicate entry from an array.
Click me to see the solution

45. Multi-Dimensional Array Difference using array_udiff

Write a PHP script to do a multi-dimensional difference, i.e. returns values of the first array that are not in the second array.
Note : Use array_udiff() function.
Click me to see the solution

46. Check if All Array Values Are Strings

Write a PHP function to check whether all array values are strings or not.
Click me to see the solution

47. Get an Array with First Key and Value

Write a PHP function to get an array with the first key and value.

Click me to see the solution

48. Set Union of Two Arrays

Write a PHP function to set union of two arrays.
Click me to see the solution

49. Get Array Entries with Specific Keys

Write a PHP script to get an array containing all the entries of an array which have the keys that are present in another array.
Test Data : 1st array : ('c1' => 'Red', 'c2' => 'Green', 'c3' => 'White', c4 => 'Black')
2nd array : ('c2', 'c4')
Output :
Array
(
[c2] => Green
[c4] => Black
)

Click me to see the solution

50. Get Last Array Value Without Affecting Pointer

Write a PHP script to get the last value of an array without affecting the pointer.
Click me to see the solution

51. Filter Out Elements with Certain Key-Names

Write a PHP program to filter out some elements with certain key-names.
Test Data :
1st array : ('c1' => 'Red', 'c2' => 'Green', 'c3' => 'White', c4 => 'Black')
2nd array : ('c2', 'c4')
Output :
Array
(
[c1] => Red
[c3] => White
)

Click me to see the solution

52. Filter a Multi-Dimensional Array by Value

Write a PHP function to filter a multi-dimensional array. The function will return those items that will match with the specified value.
Click me to see the solution

53. Delete Specific Value Using array_filter

Write a PHP script to delete a specific value from an array using array_filter() function.
Click me to see the solution

54. Remove All White Spaces in Array

Write a PHP script to remove all white spaces in an array.
Click me to see the solution

55. Convert String to Array (Trim and Remove Empty Lines)

Write a PHP function to convert a string to an array (trimming every line and remove empty lines).
Click me to see the solution

56. Create Two-Dimensional Array (4x4) Initialized to 10

Write a PHP script to create a two-dimensional array (4x4), initialized to 10.
Click me to see the solution

57. Compare Two Multidimensional Arrays for Difference

Write a PHP function to compares two multidimensional arrays and returns the difference.
Click me to see the solution

58. Combine Two Arrays (Keys and Values)

Write a PHP script to combine (using one array for keys and another for its values) the following two arrays.
('x', 'y', 'y'), (10, 20, 30)
Click me to see the solution

59. Create a Range-Like Array from a String

Write a PHP program to create a range like the following array.
Array
(
[20] => 2
[21] => 3
[22] => 4
[23] => 5
[24] => 6
[25] => 7
)

Click me to see the solution

PHP Code Editor:



More to Come !

Do not submit any solution of the above exercises at here, if you want to contribute go to the appropriate exercise page.



Follow us on Facebook and Twitter for latest update.