w3resource
w3resource logo

PHP Array Exercises : Remove a specified duplicate entry from an array

(追記) (追記ここまで)
(追記) (追記ここまで)

44. Remove Specified Duplicate Entry from Array

Write a PHP a function to remove a specified duplicate entry from an array.

Sample Solution:

PHP Code:

<?php
// Define a function to remove a specified number of occurrences of a value from an array
function array_uniq($my_array, $value) 
{ 
 $count = 0; 
 
 // Iterate through the array
 foreach($my_array as $array_key => $array_value) 
 { 
 // If more than 0 occurrences and the current value matches the specified value, unset it
 if (($count> 0) && ($array_value == $value)) 
 { 
 unset($my_array[$array_key]); 
 } 
 
 // If the current value matches the specified value, increment the count
 if ($array_value == $value) $count++; 
 } 
 
 // Remove any null or empty elements from the array
 return array_filter($my_array); 
} 
// Example usage: an array of numbers
$numbers = array(4, 5, 6, 7, 4, 7, 8);
// Call the function with the array and a value to remove
print_r(array_uniq($numbers, 7));
?>

Output:

Array 
( 
 [0] => 4 
 [1] => 5 
 [2] => 6 
 [3] => 7 
 [4] => 4 
 [6] => 8 
) 

Flowchart:

Flowchart: PHP - Remove a specified, duplicate entry from an array

For more Practice: Solve these Related Problems:

  • Write a PHP function to remove the first occurrence of a specified duplicate value from an array and return the cleaned array.
  • Write a PHP script to identify and remove a given duplicate entry from an array, ensuring only one instance is removed.
  • Write a PHP program to filter out a specific duplicate value from an array using array_filter() and reindex the array.
  • Write a PHP script to remove all but one occurrence of a specified element from an array and then display the final result.

Go to:


PREV : Merge Two Comma-Separated Lists with Unique Values.
NEXT : Multi-Dimensional Array Difference using array_udiff.

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.



Follow us on Facebook and Twitter for latest update.

(追記) (追記ここまで)


(追記) (追記ここまで)
(追記) (追記ここまで)


AltStyle によって変換されたページ (->オリジナル) /