If the $gymnast object is not in the $gymnasts array, I add it to my table. However, when I add the same object to the array, in_array() fails (returns 1) and the duplicate object is added to the array. Using print_r, I saw that the $gymnast object is clearly the same as the first element in the $gymnasts array, so why is this happening? How do I fix this?
$gymnasts array
Array ( [0] => Gymnast Object ( [name] => Nastia Liukin [age] => 27 [height] => 5' 3" [olympicYear] => 2008 [medalCount] => 5 [image] => nastia.jpg ) [1] => Gymnast Object ( [name] => Shawn Johnson [age] => 25 [height] => 4' 11" [olympicYear] => 2008 [medalCount] => 4 [image] => shawn.jpg ))
$gymnast object
Gymnast Object ( [name] => Nastia Liukin [age] => 27 [height] => 5' 3" [olympicYear] => 2008 [medalCount] => 5 [image] => nastia.jpg )
index.php
<?php
function isDuplicateEntry($gymnast, $gymnasts) {
foreach ($gymnasts as $gym) {
$gymArr = get_object_vars($gym);
$gymnastArr = get_object_vars($gymnast);
if (count(array_diff($gymnastArr, $gymArr)) == 0) { //gymnast object already exists in array
return true;
}
else {
return false;
}
}
}
//Add gymnast when press add submit button
if(isset($_POST['add'])){
//Set gymnast array to all gymnasts in data.txt
$gymnasts = read_file($filename);
//If form has valid elements & no duplicats, add to data.txt file
if($valid_name && $valid_age && $valid_feet && $valid_inches && $valid_olympicYear && $valid_medalCount && $valid_image){
$gymnast = get_gymnast_from_form();
//Make sure gymnast is not null
if(!is_null($gymnast)){
//Prevent from adding duplicates
if(!isDuplicateEntry($gymnast, $gymnasts)){
//Write task to file
write_file($filename, $gymnast);
//Add gymnast to global var gymnasts array
$gymnasts[] = $gymnast;
echo'<div class ="title">Gymnast Added!</div>';
}
}
}
?>