checkopenport
checkopenport

Reputation: 121

Delete duplicate string in array

In fact im working in a small php script , I'm using simple html dom to get some tags for a website, any way this is the code that i'm using

 if( strpos($a, '#') !== false ) 
{
    if( strpos($a, 'page') !== false ){}
        else
        {
            if( strpos($a, '#') !== false ){}
                else{
                    $items[] = $a;
                }
        }
}

I want to delete duplicate string in the array $items.

Upvotes: 0

Views: 100

Answers (3)

Dan
Dan

Reputation: 209

If you can't check for already added items for some reason (as previously suggested) you could take a look at the array_unique() method.

/edit: This is unrelated to the question, but just in case that the snippet you posted is your actual code: you should really not use if( strpos($a, 'page') !== false ){} else ...

Just invert the condition and place the code in the if block:

if (strpos($a, 'page') === false) {
    // your code here
}

Upvotes: 0

Tom G
Tom G

Reputation: 3650

This is from a comment of php.net (https://www.php.net/function.array-unique)

<?php
    $input = array("a" => "green", "red", "b" => "green", "blue", "red");
    $result = array_unique($input);
    print_r($result);
?>

Output: Array ( [a] => green [0] => red [1] => blue )

Thanks Mark!

Upvotes: 1

user399666
user399666

Reputation: 19879

Why not just check to see if the string has already been added?

if( strpos($a, '#') !== false ) 
{
    if( strpos($a, 'page') !== false ){}
        else
        {
            if( strpos($a, '#') !== false ){}
                else{
                    if(!in_array($a, $items)){
                        $items[] = $a;
                    }
                }
        }
}

Upvotes: 1

Related Questions