1

I have an array where I'm trying to find the unique values. I've seen many answers for this type of thing, but I can't understand how to apply them to my situation. Thanks in advance for the help, as I'm learning.

    Array([0] => Array ( [department] => value1)
          [1] => Array ( [department] => value1)
          [2] => Array ( [department] => value2)
          [3] => Array ( [department] => value2)
          [4] => Array ( [department] => value3)
          [5] => Array ( [department] => value3))

So I want to pull out value1, value2 and value3 so I can populate them into a select box using foreach, but I am always receiving a list showing all of the instance of each value above (value1, value1, value2, value2, value3, value3).

1
  • 3
    Why don't you do that in database? SELECT DISTINCT department ... Commented Jan 20, 2014 at 11:16

1 Answer 1

7
$departments = array();
foreach ($personnel_list as $part) {
    $departments[] = $part['department'];
}
$departments = array_unique($departments);
Sign up to request clarification or add additional context in comments.

3 Comments

array_map(function($i) { return $i['department']; }, $array);
Thank you SO much! I'm still having one issue. When I echo the results, one of the values is 'Array'. How can I get rid of that one? Below is my final code $personnel_list2 = $personnel_list; foreach ($personnel_list2 as $part) { $personnel_list2[] = $part['department']; } $departments = array_unique($personnel_list2); foreach ($departments as $depts) { echo '<option value="' . $depts. '">' . $depts. '</option>'; }
@NotAnotherCliche, the foreach() loop was meant to go over the array you posted. If that array is stored in a variable called $personnel_list, please see the updated answer (foreach loops through $personnel_list, then for each entry, it adds its department in the $departments array).

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.