Results 1 to 3 of 3

Thread: Replace value in array?

  1. #1
    Join Date
    Jan 2007
    Posts
    25
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default Replace value in array?

    I have the following array
    PHP Code:
    $a=array("a"=>"Dog","b"=>"Cat","c"=>"Horse"); 
    I want to be able to replace "Dog" to "<b>DOG</b>"

    I tried str_replace but it didn't work.
    PHP Code:
    str_replace("dog""<b>DOG</b>"$a); 
    Please help.

  2. #2
    Join Date
    Jan 2007
    Posts
    25
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default One more question:

    Is it possible to make any value in an array the first one?

    I have this array:
    PHP Code:
    $a=array("a"=>"Dog","b"=>"Cat","c"=>"Horse"); 
    I want to move horse or cat so it is the first value
    PHP Code:
    $a=array("c"=>"Horse","a"=>"Dog","b"=>"Cat");
    $a=array("b"=>"Cat","a"=>"Dog","c"=>"Horse"); 

  3. #3
    Join Date
    Sep 2006
    Location
    St. George, UT
    Posts
    2,769
    Thanks
    3
    Thanked 157 Times in 155 Posts

    Default

    Quote Originally Posted by jacksont123 View Post
    I have the following array
    PHP Code:
    $a=array("a"=>"Dog","b"=>"Cat","c"=>"Horse"); 
    I want to be able to replace "Dog" to "<b>DOG</b>"

    I tried str_replace but it didn't work.
    PHP Code:
    str_replace("dog""<b>DOG</b>"$a); 
    Please help.
    Probably why the str_replace didn't work is because you need to have it actually match what you are searching and replacing (you could probably use Regular expressions for this, but for your example use the following).

    Code:
    $a=array("a"=>"Dog","b"=>"Cat","c"=>"Horse");
    
    $string = str_replace('Dog', '<b>DOG</b>', $a);
    
    echo $string;
    Notice how I matched the case in the str_replace function to that of the word "Dog" in the array. The above snippet (spelling?) will produce the following:

    DOG
    Hope this helps.
    "Computer games don't affect kids; I mean if Pac-Man affected us as kids, we'd all be running around in darkened rooms, munching magic pills and listening to repetitive electronic music." - Kristian Wilson, Nintendo, Inc, 1989
    TheUnlimitedHost | The Testing Site | Southern Utah Web Hosting and Design

Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •