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
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";
}

?>

Link to comment
Share on other sites

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

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • 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.