Home >Backend Development >PHP Tutorial >How to correctly implement PHP to delete duplicate elements from an array_PHP Tutorial
Our actual operationThe PHP sample code for deleting duplicate elements from an array is as follows:
<ol class="dp-xml"> <li class="alt"><span><span class="tag"><strong><font color="#006699"><?</FONT></STRONG></SPAN><SPAN> </SPAN></SPAN><LI class=""><SPAN> </SPAN><LI class=alt><SPAN></SPAN><SPAN class=tag-name><STRONG><FONT color=#006699>function</FONT></STRONG></SPAN><SPAN> uniqueArray($array) </SPAN></SPAN><LI class=""><SPAN> </SPAN><LI class=alt><SPAN>{ </SPAN><LI class=""><SPAN> </SPAN><LI class=alt><SPAN>// Get unique elts as keys in assoc. array </SPAN><LI class=""><SPAN> </SPAN><LI class=alt><SPAN>for ($</SPAN><SPAN class=attribute><FONT color=#ff0000>i</FONT></SPAN><SPAN>=</SPAN><SPAN class=attribute-value><FONT color=#0000ff>0</FONT></SPAN><SPAN>,$</SPAN><SPAN class=attribute><FONT color=#ff0000>n</FONT></SPAN><SPAN>=</SPAN><SPAN class=attribute-value><FONT color=#0000ff>count</FONT></SPAN><SPAN>($array, 1);$i</SPAN><SPAN class=tag><STRONG><FONT color=#006699><</FONT></STRONG></SPAN><SPAN>$n;$i++) </SPAN></SPAN><LI class=""><SPAN> </SPAN><LI class=alt><SPAN>$u_array[$array[$i]] = 1; </SPAN><LI class=""><SPAN> </SPAN><LI class=alt><SPAN> </SPAN><LI class=""><SPAN> </SPAN><LI class=alt><SPAN>// Copy keys only into another array </SPAN><LI class=""><SPAN> </SPAN><LI class=alt><SPAN>reset($u_array, 1); </SPAN><LI class=""><SPAN> </SPAN><LI class=alt><SPAN>for ($</SPAN><SPAN class=attribute><FONT color=#ff0000>i</FONT></SPAN><SPAN>=</SPAN><SPAN class=attribute-value><FONT color=#0000ff>0</FONT></SPAN><SPAN>,$</SPAN><SPAN class=attribute><FONT color=#ff0000>n</FONT></SPAN><SPAN>=</SPAN><SPAN class=attribute-value><FONT color=#0000ff>count</FONT></SPAN><SPAN>($u_array, 1);$i</SPAN><SPAN class=tag><STRONG><FONT color=#006699><</FONT></STRONG></SPAN><SPAN>$n;$i++) { </SPAN></SPAN><LI class=""><SPAN> </SPAN><LI class=alt><SPAN>$unduplicated_array[] = key($u_array, 1); </SPAN><LI class=""><SPAN> </SPAN><LI class=alt><SPAN>next($u_array, 1); </SPAN><LI class=""><SPAN> </SPAN><LI class=alt><SPAN>} </SPAN><LI class=""><SPAN> </SPAN><LI class=alt><SPAN>return $unduplicated_array; </SPAN><LI class=""><SPAN> </SPAN><LI class=alt><SPAN>} </SPAN><LI class=""><SPAN> </SPAN><LI class=alt><SPAN></SPAN><SPAN class=tag><STRONG><FONT color=#006699>?></font></strong></span><span> </span></span></li> <li class=""><span> </span></li> </ol>
The above string of code is the specific implementation method of PHP deleting duplicate elements from an array.