Jump to content

Check for Duplicate Values in Array


onlyican

Recommended Posts

Hey people

I have 3 arrays

and I want to make sure the values from all of the arrays are different.

 

The way I was thinking of doing it is something like

$NewArray = array();

foreach($MyArray as $value){

if(!in_array($value, $NewArray){

$NewArray[] = $value;

}else{

return "Duplicate Found";

}

}

 

But does anyone know an easier way?

 

Link to comment
https://forums.phpfreaks.com/topic/36656-check-for-duplicate-values-in-array/
Share on other sites

Example:


<?php

$arr1 = array(1,5,7,6);
$arr2 = array(3,;
$arr3 = array(2,0,6);

$arr_all = array_merge($arr1,$arr2,$arr3);

if($arr_all == array_unique($arr_all))
{
  echo "All values are unique";
}
else
{
  echo "One or more values was identical";
}

?>

ok, that bets what I done

 

I done this

<?php

function ValidateSeatingKeys(){
$ColumnsLeft = isset($_POST["ColumnsLeft"]) ? $_POST["ColumnsLeft"] : array();

$ColumnsMiddle = isset($_POST["ColumnsMiddle"]) ? $_POST["ColumnsMiddle"] : array();

$ColumnsRight = isset($_POST["ColumnsRight"]) ? $_POST["ColumnsRight"] : array();

$RowsTop = isset($_POST["RowsTop"]) ? $_POST["RowsTop"] : array();

$RowsMiddle = isset($_POST["RowsMiddle"]) ? $_POST["RowsMiddle"] : array();

$RowsBottom = isset($_POST["RowsBottom"]) ? $_POST["RowsBottom"] : array();
$Columns = array_merge($ColumnsLeft, $ColumnsMiddle, $ColumnsRight);
$Rows = array_merge($RowsTop, $RowsMiddle, $RowsBottom);
$Rows = array_merge($RowsTop, $RowsMiddle, $RowsBottom);

$UniqueCols = array();
$UniqueRows = array();
$DupCols = array();
$DupRows = array();
foreach($Columns as $Column){
	if(!in_array($Column, $UniqueCols)){
		$UniqueCols[] = $Column;
	}else{
		$DupCols[] = $Column;
	}
}

foreach($Rows as $Row){
	if(!in_array($Row, $UniqueRows)){
		$UniqueRows[] = $Row;
	}else{
		$DupRows[] = $Row;
	}
}
if(count($DupCols) != 0 && count($DupRows) != 0){
	return true;
}else{
	return false;
}

}
?>

 

Cheers

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.