1

Is there any way to avoid creates duplicate object name without using loop?

$venue = array();

if(loop for checking duplicate OBJ){
        $temp = some_var which fetch from database;

        //If it's not a duplicate object, creates new object 
        $venue["$temp"] = new Venue($temp);
        $venue["$temp"]->do something;
    }
    else{
        //If it's a duplicate object, don't creates new object
        $venue["$temp"]->do something;
    }

I'm trying to check duplicate object name("name") by using loop like this:

//checks name of each object in venue's array that Is it duplicate?

for($itr = 0;$itr < $count($venue);$itr+=1){
        if($venue["$temp"]->name === $name){ 
            return true; //If it's a duplicate object name return true
        }
}

The problem is when I using this loop to check, It consume a lot of time to finish the work

1 Answer 1

8

An easy way of doing this is to use another array to collect all names as array keys:

$allNames[$venue["$temp"]->name] = null; 

Then check if it's a duplicate object name by using:

array_key_exists($allNames, $name);
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks, better than mine

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.