Jump to content

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);
?>

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • 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.