Jump to content

Anyone know of a quick way to do this?


tfburges

Recommended Posts

Basically, I have an array with duplicate values and I want to go through and rename each value to the same name plus a number.

i.e. Suppose the array is (blah, bleh, bloo, blah, bloo, blip).  Then it should become (blah1, bleh, bloo1, blah2, bloo2, blip).

 

I have an idea where I would use an if statement in combination with array_count_values() and array_search() or something of the like.

The problem is that I don't know how to retrieve the value when the count is greater than 1.  And I also don't know the syntax for renaming the value with a number on the end of it.

 

Any suggestions or better ideas?

Link to comment
https://forums.phpfreaks.com/topic/114133-anyone-know-of-a-quick-way-to-do-this/
Share on other sites

After having a readup on the functions you provided, I came up with this:

<?php

$words = array('blah', 'bleh', 'bloo', 'blah', 'bloo', 'blip');

$word_count = array_count_values($words);

foreach($word_count as $word => $count)
{
    if($count > 1)
    {
        $keys = array_keys($words, $word);

        $i = 1;
        foreach($keys as $key)
        {
            $words[$key] = $word . $i;

            $i++;
        }
    }
}

echo '<pre>' . print_r($words, true) . '</pre>';

?>

also:

 

<?php
  $words = array('blah', 'bleh', 'bloo', 'blah', 'bloo', 'blip');
  foreach(array_unique($words) as $word){
    $idxs = array_keys($words,$word);
    if(count($idxs) > 1){
      foreach($idxs as $n=>$idx){
        $words[$idx] = $word.($n+1);
      }
    }
  }
  print_r($words);
?>

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.