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? Quote Link to comment Share on other sites More sharing options...
Solution akphidelt2007 Posted April 29, 2013 Solution Share Posted April 29, 2013 (edited) 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 April 29, 2013 by akphidelt2007 Quote Link to comment 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. Quote Link to comment Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.