John Davidson

How can I return this array without duplicates in PHP?

0 comments
Message:


I´m trying to get this array


 [24]=>
array(2) {
[0]=>
string(1) "21"
[1]=>
string(1) "22"
}

So far I have this:


function Job($conn){
$array = array();
foreach(array_unique($_SESSION['ROLES']) as $value)
{
$sql="SELECT employee,task FROM table WHERE id={$value} AND employee=24";//echo($sql);
$result = $conn->executeSQL($sql);
foreach($result as $value)
{
$array[$value['employee']][] = $value['task'];

}
}

return $array;

}

Which returns the tasks for two values I have store in $_SESSION['ROLES'] but if there are duplicates I need to remove them :


 [24]=>
array(4) {
[0]=>
string(1) "21"
[1]=>
string(1) "22"
[2]=>
string(1) "21"
[3]=>
string(1) "22"
}


My Answer:
To remove duplicates from an array in PHP, you can use the `array_unique()` function. Here's an example of how you can use it:

php
// Original array with duplicates
$array = [24, 24, 36, 48, 24, 36];

// Remove duplicates
$uniqueArray = array_unique($array);

// Print the unique array
print_r($uniqueArray);


This will output:


Array
(
[0] => 24
[2] => 36
[3] => 48
)


As you can see, the duplicates have been removed from the original array.

Rate this post

4 of 5 based on 1084 votes

Comments




© 2024 Hayatsk.info - Personal Blogs Platform. All Rights Reserved.
Create blog  |  Privacy Policy  |  Terms & Conditions  |  Contact Us