Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 6827489
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 26, 20262026-05-26T22:16:18+00:00 2026-05-26T22:16:18+00:00

I wrote a few lines of code in PHP to rename duplicate values in

  • 0

I wrote a few lines of code in PHP to rename duplicate values in an array (with some inspiration from here).
Basically, I go through the original array ($headers[]), while using the keys of another array ($header_test[]) to keep track of duplicates. If there is a duplicate, I change the value of that element in $headers[].

But the weird thing is that I was not getting the right results by passing by reference in the foreach. I had to actually set the values by using the full $array_name[$key] = $new_value format. Why is that?

(Spoiler alert: VolkerK’s answer is correct – need to unset $header (the foreach “$value” variable) and then it works.)

Here:

Using this input:

$headers = array('Abc 123 ghi',
            'dangdarn',
            'oops32',
            'poss dup',
            'poss dup',
            'pos  _s_ dup',
            'bad chars\'& 3% 9'
           );

Then applying this custom function which I don’t think would affect the problem at hand:

    function mysql_clean_string($string) {
    //remove non alnum characters
    $string =  preg_replace("/[^a-zA-Z0-9\s]/", "_", $string);

    // replace 1+ spaces or 1+ '_' with a single '_'
    $string =  preg_replace("/[ _]+/", "_", $string);

    $string = trim($string,'_');

    if(strlen($string) > 20) {
        $string = substr_replace($string,'',strpos($string,'_',20));
    }

    $string = strtolower($string);

    return $string;
}

array_walk($headers,'mysql_clean_string'); // limit headers to alnum chars

Passing the array values by reference doesn’t work right (see below for var_dump()):

    $header_test = array();
    foreach($headers as &$header) { //passing by reference
        $temp = $header;
        if(array_key_exists($temp,$header_test)) {

            **$header = $header . '_' . $header_test[$header];**
            $header_test[$temp]++; 
            unset($temp);
        } else {
            $header_test[$temp] = 1;
        }
    }

//here is the solution VolkerK suggested and it works:
unset($header);

Here are the var_dump outputs with incorrect results (duplicate values and notice “&” at headers[6], and missing last value):

  ["headers"]=>
  array(7) {
    [0]=>
    string(11) "abc_123_ghi"
    [1]=>
    string(8) "dangdarn"
    [2]=>
    string(6) "oops32"
    [3]=>
    **string(8) "poss_dup"**
    [4]=>
    string(10) "poss_dup_1"
    [5]=>
    string(9) "pos_s_dup"
    [6]=>
    **&string(8) "poss_dup"**
  }
  ["header_test"]=>
  array(6) {
    ["abc_123_ghi"]=>
    int(1)
    ["dangdarn"]=>
    int(1)
    ["oops32"]=>
    int(1)
    ["poss_dup"]=>
    int(2)
    ["pos_s_dup"]=>
    int(1)
    ["bad_chars_3_9"]=>
    int(1)
  }

And now here is what works, which is to use $original_array[$key] = $new_value format:

$header_test = array();
foreach($headers as $key => $header) {
    $temp = $header;
    if(array_key_exists($temp,$header_test)) {

        **$headers[$key] = $header . '_' . $header_test[$header];**
        $header_test[$temp]++; 
        unset($temp);
    } else {
        $header_test[$temp] = 1;
    }
}

var_dump:

  ["headers"]=>
  array(7) {
    [0]=>
    string(11) "abc_123_ghi"
    [1]=>
    string(8) "dangdarn"
    [2]=>
    string(6) "oops32"
    **[3]=>
    string(8) "poss_dup"
    [4]=>
    string(10) "poss_dup_1"**
    [5]=>
    string(9) "pos_s_dup"
    **[6]=>
    string(13) "bad_chars_3_9"**
  }
  ["header_test"]=>
  array(6) {
    ["abc_123_ghi"]=>
    int(1)
    ["dangdarn"]=>
    int(1)
    ["oops32"]=>
    int(1)
    ["poss_dup"]=>
    int(2)
    ["pos_s_dup"]=>
    int(1)
    ["bad_chars_3_9"]=>
    int(1)
  }

VolkerK came up with the solution. Besides his other good suggestions, the key thing was unsetting $header after the foreach loop.

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-05-26T22:16:19+00:00Added an answer on May 26, 2026 at 10:16 pm

    just taking your code

    <?php
    $headers = array('Abc 123 ghi',
                'dangdarn',
                'oops32',
                'poss dup',
                'poss dup',
                'pos  _s_ dup',
                'bad chars\'& 3% 9'
               );
    
    $header_test = array();
    foreach($headers as &$header) { //passing by reference
        $temp = $header;
        if(array_key_exists($temp,$header_test)) {
    
            $header = $header . '_' . $header_test[$header];
            $header_test[$temp]++; 
            unset($temp);
        } else {
            $header_test[$temp] = 1;
        }
    }
    
    var_dump($headers);
    

    produces

    array(7) {
      [0]=>
      string(11) "Abc 123 ghi"
      [1]=>
      string(8) "dangdarn"
      [2]=>
      string(6) "oops32"
      [3]=>
      string(8) "poss dup"
      [4]=>
      string(10) "poss dup_1"
      [5]=>
      string(12) "pos  _s_ dup"
      [6]=>
      &string(16) "bad chars'& 3% 9"
    }
    

    on my machine using php 5.3.5/win32. Looks like your “real” code does something else to $header in and/or after the loop.

    A bit simplified (eliminating $tmp):

    <?php
    $headers = getData();
    $header_test = array();
    foreach($headers as &$header) { //passing by reference
        if( array_key_exists($header, $header_test) ) {
            $header = $header . '_' . $header_test[$header]++;
        }
        else {
            $header_test[$header] = 1;
        }
    }
    
    // removes the reference that's causing the & in front
    // of the last element of $headers in the output of var_dump
    // if $headers can be empty you need to guard this
    // to avoid "undefined variable 'header' warning.
    // Probably better to put this code in a function
    // so that $header can fall out of scope automagically
    unset($header); 
    
    var_dump($headers);
    
    function getData() {
        return array('Abc 123 ghi',
            'dangdarn',
            'oops32',
            'poss dup',
            'poss dup',
            'pos  _s_ dup',
            'bad chars\'& 3% 9',
            'poss dup',
            'poss dup'
        );
    }
    

    prints

    array(9) {
      [0]=>
      string(11) "Abc 123 ghi"
      [1]=>
      string(8) "dangdarn"
      [2]=>
      string(6) "oops32"
      [3]=>
      string(8) "poss dup"
      [4]=>
      string(10) "poss dup_1"
      [5]=>
      string(12) "pos  _s_ dup"
      [6]=>
      string(16) "bad chars'& 3% 9"
      [7]=>
      string(10) "poss dup_2"
      [8]=>
      string(10) "poss dup_3"
    }
    
    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I wrote few lines of code which doesn't work correctly. Why? Could sb explain
I'm a beginner in PHP. 2 days ago I write few lines of code
I'm catching up on pointers. I wrote down a few lines of code to
Last week I wrote a few lines of code in C# to fire up
I was thinking about a code that I wrote a few years ago in
By code snippet execution, I mean the ability to write a few lines of
I have a few lines of code that I want to run asynchronously in
I have a few lines of code that start something like this: $trailheads =
I'm trying to write a few lines of code to make a case insensitive
A few months ago I wrote a website for a customer using PHP 5.3.

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.