Jump to content

substr_replace seems to fail


Go to solution Solved by akphidelt2007,

Recommended Posts

I am playing with genetics and language, and can't get substr_replace to work. In the code fragment below I expect a mutation to change a character to another random character at random intervals. I put in a die to kill the process after the first replacement.

print_r($individuals);
foreach ($individuals as $key => $genome) {
            for ($x=0; $x<$num_offspring; $x++){
                $progeny[($key*$x)+$x]=$individuals[$key];
                for ($letter=0; $letter<strlen($progeny[$key*$x+$x]); $letter++){
                    //
                    if ((mt_rand(1,100))<=$mutation_rate){
                        //echo $x;
                        //print_r ($chars);
                        $replacement = $chars[mt_rand(0, (count($chars)-1))];
                        echo "<p>replacement: $replacement letter $letter x $x progeny # ";
                        echo $key*$x+$x."</p>\n";

                        echo "substr_replace(".$progeny[$key*$x+$x].",$replacement, $letter, 1)";
                        substr_replace($progeny[$key*$x+$x],$replacement, $letter, 1);
                        die($progeny[$key*$x+$x]);
                    }
                            
                }
}
        }

and I get output like this:

cTRcXiAirWYhWJTXp.gMFsHkUIqmle.WEJEe.Umx
Array ( [0] => cTRcXiAirWYhWJTXp.gMFsHkUIqmle.WEJEe.Umx )

replacement: e letter 0 x 0 progeny # 0
substr_replace(cTRcXiAirWYhWJTXp.gMFsHkUIqmle.WEJEe.Umx,e, 0, 1)cTRcXiAirWYhWJTXp.gMFsHkUIqmle.WEJEe.Umx

I expect that the first letter would change from a c to an e but it doesn't. I must be using substr_replace wrong, but I can't see where. What am I missing?

Link to comment
https://forums.phpfreaks.com/topic/277398-substr_replace-seems-to-fail/
Share on other sites

  • Solution

substr_replace does not change the array. You have to store it in a variable or include it in the die statement

 

So when you say die($progeny[$key*$x+$x]);... it is still going to contain the same value that it was before substr_replace.

 

Do...

$replace = substr_replace($progeny[$key*$x+$x],$replacement, $letter, 1);
die($replace);
Edited by akphidelt2007
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.