2

I'm fairly new to PHP and I have a question.

I'm trying to make a function that adds tags to a text. My function works but the order of the tags in the array returned is wrong.

How can I change the order, please

Thanks for any help.

 <?php
    
     $tags = [
        'animals' => ['cat', 'dog', 'horse', 'ferret'],
        'nature' => ['walk', 'outdoor', 'tree', 'plant']];
        
        
        function getTags(string $text, array $tags): array
        {
            $lowerC = strtolower($text);
            $str = preg_replace("/[^A-Za-z\'\- ]/", '', $lowerC);
            $arrayT = explode(" ", $str);
        
            $tagArray = [];
            foreach ($tags as $tag => $value) {
                
                    if (array_intersect( $value, $arrayT )) {
                        $tagArray[] = $tag;
                }
        
            }   return $tagArray;
          
        }
    
    
    $res = getTags('During my walk, I met a white horse', $tags);
    var_dump($res); // returns ['animals', 'nature'] but I'm trying to get ['nature', 'animals']
3
  • They are coming back out in the order they are in your tag array. If you want the order to be different change their order in $tags
    – John Conde
    Feb 13, 2021 at 13:17
  • Why do you expect if to return nature first, what is the logic (first encountered word, most words?)
    – Nigel Ren
    Feb 13, 2021 at 13:27
  • Yes the first tag in the array must be 'nature' because the word 'walk' comes before 'horse'. Thanks Feb 13, 2021 at 13:45

1 Answer 1

1

If you want to get 'nature' first, because 'walk' comes before 'horse', you need to iterate over the words first, not over the tags.

$tags = [
    'animals' => ['cat', 'dog', 'horse', 'ferret'],
    'nature' => ['walk', 'outdoor', 'tree', 'plant'],
];
    
    
function getTags(string $text, array $tags): array
{
    $lowerC = strtolower($text);
    $str = preg_replace("/[^A-Za-z\'\- ]/", '', $lowerC);
    $arrayT = explode(" ", $str);

    $tagArray = [];
    foreach ($arrayT as $word) {
        // find tag for this word
        foreach ($tags as $cat => $values) {
            if (in_array($word, $values)) {
                // append the tag to the list
                $tagArray[] = $cat;
            }
        }
    }
    
    // remove duplicates
    return array_unique($tagArray);
  
}


$res = getTags('During my walk, I met a white horse', $tags);
var_dump($res);

Output :

array(2) {
  [0]=>
  string(6) "nature"
  [1]=>
  string(7) "animals"
}

EDIT

As @GeorgeGarchagudashvili mentionned, the code could be optimized by preparing an array for comparison. Here is a way :

function getTags(string $text, array $tags): array
{
    $lowerC = strtolower($text);
    $str = preg_replace("/[^A-Za-z\'\- ]/", '', $lowerC);
    $arrayT = explode(" ", $str);
    
    // Prepare tags for searching
    $searchTags = [];
    foreach ($tags as $cat => $values) {
        foreach ($values as $word) {
            $searchTags[$word] = $cat;
        }
    }

    $tagArray = [];
    foreach ($arrayT as $word) 
    {
        // find tag for this word
        if (isset($searchTags[$word])) 
        {
            // append the tag to the list
            $tagArray[] = $searchTags[$word];
        }
    }
    
    // remove duplicates
    return array_unique($tagArray);
  
}
2
  • 1
    You could optimize your code's runtime by preparing tags array for comparison and iterating words array after. N*M => N+M
    – George G
    Feb 13, 2021 at 15:02
  • 1
    Agree, I'll update the answer. Thank you @GeorgeGarchagudashvili
    – Syscall
    Feb 13, 2021 at 15:03

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.