0

I am working on using in_array() to check if a Course object called (appropriately named) Course is in an array.

One issue I am having is, I want to use a specific property within my Course object to do the object comparison, instead of comparison of the entire object.

Specifically, I want to use the $course->getShortName() to do the comparison. Why? Because all the other private variables within my Course object can be different, except for the short_name property which can stay the same, and that's why I want to use it to do the object property.

Method that does the comparison:

public function overlap($courses, $course_temp) {
    for ($i = 0; $i < count($courses); $i = $i + 1) {
        if ($this->overlapCourses($courses[$i], $course_temp)) {
            // Push the class that is conflicted to the conflictedClass
            // array
            // TODO: Figure out why it's being added to the list
            if(!in_array($courses[$i], $this->conflictClasses)) {
                array_push($this->conflictClasses, $courses[$i]);
            }

            // Push the class that is conflicted with to the
            // conflictedClass array
            // TODO: Figure out why it's being added to the list
            if(!in_array($course_temp, $this->conflictClasses)) {
                array_push($this->conflictClasses, $course_temp);
            }
            return false;
        }
    }
    return false;
}

Getter from my Course class

public function getShortName(){
    return $this->short_name;
}

tl;dr: Instead of compare object, compare one property of the object

1

1 Answer 1

1

I cannot see any existing function that would apply here. You could use array_filter to perform what you want :

function object_in_array($needle, array $array, $method) {
    $propertyToMatch = $needle->$method();
    // the $matches var will contain all the objects that have the property matching your object property
    $matches = array_filter($array, function($object) use ($propertyToMatch, $method) {
        return $propertyToMatch === $object->$method();
    });

    // If there is at least 1 result, your object property is matching one of your array of objects
    return count($matches) > 0;
}

Usage

if (object_in_array($myObject, $courses, 'getShortName')) {
    ....
}

Of course you should verify if the $method method exists and throw exceptions if not.

Sign up to request clarification or add additional context in comments.

2 Comments

Thanks! What's the big O of array_filter?
sorry ? I do not understand your question

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.