How to edit an object property within an array of objects using PHP?

In the code below, I create an object instance $T, give its properties values, and add it to my array of objects called $teacherObjArray. However, where I'm having trouble is if the object instance already exists (this is checked by the teacherExists() function)... how does does the program know which $T object I am accessing? In other words, How can I program it to where it UPDATES the CORRECT within the array of objects? My definition of correct is where $teacherName is the same as object property LName. I appreciate the help :)
function teacherExists($teacherObjArray, $teacherName) {
foreach ($teacherObjArray as $Teacher) {
if ($Teacher->LName == $teacherName) return true; //can i return index here?
}
return false;
}
while(sizeOf($r) > 0)
{
if (!teacherExists($teacherObjArray, $teacherName)) {
$T = new Teacher($teachernName, $teacherMaxLoad, $classPeriod);
$T->LName = $teacherName;
$T->MaxLoad = $teacherMaxLoad;
$T->addPeriod($classPeriod);
array_push($teacherObjArray, $T);
//create course object
$C = new Course($courseNumber, $courseName, $teacherName, $classPeriod);
$C->CourseNumber=$courseNumber;
$C->CourseName=$courseName;
$C->CourseTeacher=$teacherName;
$C->CoursePeriod=$classPeriod;
maintenance($r, $teacherName, $classPeriod, $cn);
}
//updates already existing object in array of objects
elseif (teacherExists($teacherObjArray, $teacherName))
{
//get teacher object where its LName property is equal to $teacherName
$T->addPeriod($classPeriod);
maintenance($r, $teacherName, $classPeriod, $cn);
}
}
Answer
Solution:
You can rewriteteacherExists
to return the index of the found value, orfalse
when not found:
function teacherExists($teacherObjArray, $teacherName) {
foreach ($teacherObjArray as $key => $Teacher) {
if ($Teacher->LName == $teacherName) return $key;
}
return false;
}
and then you can rewrite yourif
clause to check that the return value isfalse
:
if (($key = teacherExists($teacherObjArray, $teacherName)) === false) {
and yourelseif
clause simply becomes:
else
{
//get teacher object where its LName property is equal to $teacherName
$T = $teacherObjArray[$key];
$T->addPeriod($classPeriod);
maintenance($r, $teacherName, $classPeriod, $cn);
}
Note that since you call
maintenance($r, $teacherName, $classPeriod, $cn);
at the end of both theif
andelse
clauses, you could move it after theif
block.
Share solution ↓
Additional Information:
Link To Answer People are also looking for solutions of the problem: integrity constraint violation: 1452 cannot add or update a child row: a foreign key constraint fails
Didn't find the answer?
Our community is visited by hundreds of web development professionals every day. Ask your question and get a quick answer for free.
Similar questions
Find the answer in similar questions on our website.
Write quick answer
Do you know the answer to this question? Write a quick response to it. With your help, we will make our community stronger.