problem with str_replace in an array in a loop

Discussion in 'PHP' started by mk24, Dec 3, 2008.

  1. #1
    for ( $i = 0; $i <= count($keywordlist); $i += 1) {
    $keywordlist[$i] = str_replace("X", "Y", $keywordlist[$i]);
    }
    PHP:
    I cant seem to figure out why the above code doesnt work. I have echo statements after this bit to see if it worked, but when i use this code above the site just loads (for a bit longer than usual) and then i get NO output.

    If i create a new array, lets say $testArray and use code like below, it works!
    for ( $i = 0; $i <= count($keywordlist); $i += 1) {
    $testArray[] = str_replace("X", "Y", $keywordlist[$i]);
    }
    PHP:
    Now if i echo the components of $testArray, it works fine (notice however that i dont need assign a number for testArray, as it just appends the new string to the array). Why doesn't the code above (the very first code) work? I mean
    $keywordlist[0] = str_replace("X", "Y", $keywordlist[0]
    PHP:
    works fine, so why won't it work if i use a variable ($i) in the for loop above?

    Thanks!
     
    mk24, Dec 3, 2008 IP
  2. EricBruggema

    EricBruggema Well-Known Member

    Messages:
    1,740
    Likes Received:
    28
    Best Answers:
    13
    Trophy Points:
    175
    #2
    why not doing this

    $text = str_replace(array("from", "from1", "from2", "etc"), array("to", "to1", "to2", "toetc"), $text);

    You can use arrays in str_replace ;)
     
    EricBruggema, Dec 3, 2008 IP
  3. mk24

    mk24 Banned

    Messages:
    36
    Likes Received:
    3
    Best Answers:
    0
    Trophy Points:
    0
    #3
    Thanks for your help, but I was trying to replace only one character in every string of my array, not do multiple replacements for a single string. for example, if these were the objects of my array:
    "sampleX"
    "textX"

    i would want them changed to:
    "sampleY"
    "textY".

    Simply changing all occurences of "X" to "Y" in every string of my array.
     
    mk24, Dec 4, 2008 IP