How To, PHP Beginners

Check Duplicate Values in Foreach PHP

To Check Duplicate Values in Foreach PHP, we use an example where we find duplicate values in an array without using PHP...

Written by Bikash · 1 min read >

To Check Duplicate Values in Foreach PHP, we use an example where we find duplicate values in an array without using PHP inbuilt function, and then on the second method, we find duplicate values in an associative array with the help of array_search() function.

Check Duplicate Values in Foreach PHP
Check Duplicate Values in Foreach PHP

Here we discuss two methods to find duplicate values in array using PHP foreach loop,

  • Using array_search() function and foreach loop.
  • Using two foreach loops.

In this process, first, we create an associative array with static values, then we do both operations where we use foreach loop.

Example of Find Duplicate Values in Array PHP

Code Explanations:

  • On the above code, we create an associative array then we use two foreach loops to find duplicate values in array PHP.
  • We use the “name” key to check the duplicate values in the array.
  • When the first loop starts it runs according to array size and checks first value with all other values with the help of the second foreach loop.

Output:

find arrays with duplicate value for ‘name’
current key: 0
duplicate found: 2
duplicate found: 3

current key: 1

current key: 2
duplicate found: 0
duplicate found: 3

current key: 3
duplicate found: 0
duplicate found: 2

It also works for Find Duplicate Value in Foreach PHP Without Using Function this condition.

Find Duplicate Values Using Array Search Function PHP

Code Explanations:

  • Here we also use the same associative array which we use on the above code.
  • Here we only check with the array key and use array_search function to get all the array keys and match with others using foreach loop one by one.

Output:

current key: 0
search key: 0

current key: 1
search key: 1

current key: 2
search key: 0
duplicate found for item 2

current key: 3
search key: 3

Here is the complete source code to check duplicate values in an associative array with and without using PHP inbuilt function. If you get any issue with the code, you can comment below.

You can also use the array unique function. To know more you can check the official website https://www.php.net/manual/en/function.array-unique.php

Also Check:

Happy Coding..!

Was this article helpful?
YesNo
Written by Bikash
My name is Bikash Kr. Panda. I own and operate PHPCODER.TECH. I am a web Programmer by profession and working on more than 50 projects to date. Currently I am working on the web-based project and all the CMS and frameworks which are based on PHP. Profile

2 Replies to “Check Duplicate Values in Foreach PHP”

Leave a Reply

Your email address will not be published. Required fields are marked *