PHP 8.4.24 Released!

Voting

: min(six, six)?
(Example: nine)

The Note You're Voting On

Ghanshyam Katriya(anshkatriya at gmail)
11 years ago
Create multidimensional array unique for any single key index.
e.g I want to create multi dimentional unique array for specific code

Code : 
My array is like this,

<?php
$details = array(
    0 => array("id"=>"1", "name"=>"Mike",    "num"=>"9876543210"),
    1 => array("id"=>"2", "name"=>"Carissa", "num"=>"08548596258"),
    2 => array("id"=>"1", "name"=>"Mathew",  "num"=>"784581254"),
);
?>

You can make it unique for any field like id, name or num.

I have develop this function for same : 
<?php
function unique_multidim_array($array, $key) {
    $temp_array = array();
    $i = 0;
    $key_array = array();
    
    foreach($array as $val) {
        if (!in_array($val[$key], $key_array)) {
            $key_array[$i] = $val[$key];
            $temp_array[$i] = $val;
        }
        $i++;
    }
    return $temp_array;
}
?>

Now, call this function anywhere from your code,

something like this,
<?php
$details = unique_multidim_array($details,'id');
?>

Output will be like this :
<?php
$details = array(
    0 => array("id"=>"1","name"=>"Mike","num"=>"9876543210"),
    1 => array("id"=>"2","name"=>"Carissa","num"=>"08548596258"),
);
?>

<< Back to user notes page

To Top