PHP Array Exercises : Create a multidimensional unique array for any single key index
38. Multidimensional Unique Array by Key Index
Write a PHP function to create a multidimensional unique array for any single key index.
Sample Solution:
PHP Code:
<?php
// Define a function to filter unique values based on a specified key in a multidimensional array
function unique_array($my_array, $key) {
$result = array(); // Initialize an empty array to store the unique values
$i = 0; // Initialize a counter
$key_array = array(); // Initialize an array to keep track of encountered keys
// Iterate through each element in the input array
foreach($my_array as $val) {
// Check if the key value is not already present in the key array
if (!in_array($val[$key], $key_array)) {
$key_array[$i] = $val[$key]; // Store the key value in the key array
$result[$i] = $val; // Store the entire element in the result array
}
$i++; // Increment the counter
}
// Return the array containing unique values based on the specified key
return $result;
}
// Define an array of students with associated information
$students = array(
0 => array("city_id"=>"1", "name"=>"Sara", "mobile_num"=>"1111111111"),
1 => array("city_id"=>"2", "name"=>"Robin", "mobile_num"=>"2222222222"),
2 => array("city_id"=>"1", "name"=>"Sonia", "mobile_num"=>"3333333333"),
);
// Display the result of applying the unique_array function to the students array with the "city_id" key
print_r(unique_array($students, "city_id"));
?>
Output:
Array ( [0] => Array ( [city_id] => 1 [name] => Sara [mobile_num] => 1111111111 ) [1] => Array ( [city_id] => 2 [name] => Robin [mobile_num] => 2222222222 ) )
Flowchart:

For more Practice: Solve these Related Problems:
- Write a PHP function to remove duplicate sub-arrays from a multidimensional array based on a single key index.
- Write a PHP script to iterate over a multidimensional array and build a new array containing only unique values for a specified key.
- Write a PHP program to compare key values across sub-arrays and filter out duplicates to create a unique multidimensional array.
- Write a PHP function to generate a flattened array from a multidimensional input while ensuring uniqueness of a specified key.
Go to:
PREV : Count Occurrences of a Specific Value in Array.
NEXT : Remove Duplicate Values from Array.
PHP Code Editor:
Contribute your code and comments through Disqus.
What is the difficulty level of this exercise?
Test your Programming skills with w3resource's quiz.