davidannis Posted April 29, 2013 Share Posted April 29, 2013 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 More sharing options...
akphidelt2007 Posted April 29, 2013 Share Posted April 29, 2013 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); Link to comment https://forums.phpfreaks.com/topic/277398-substr_replace-seems-to-fail/#findComment-1427043 Share on other sites More sharing options...
davidannis Posted April 29, 2013 Author Share Posted April 29, 2013 I can't believe I did that. Thanks for the help. Link to comment https://forums.phpfreaks.com/topic/277398-substr_replace-seems-to-fail/#findComment-1427045 Share on other sites More sharing options...
Recommended Posts
Archived
This topic is now archived and is closed to further replies.