Log in

View Full Version : Replace value in array?



jacksont123
03-01-2007, 11:24 PM
I have the following array

$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.

str_replace("dog", "<b>DOG</b>", $a);

Please help.

jacksont123
03-02-2007, 01:02 AM
Is it possible to make any value in an array the first one?

I have this array:

$a=array("a"=>"Dog","b"=>"Cat","c"=>"Horse");

I want to move horse or cat so it is the first value

$a=array("c"=>"Horse","a"=>"Dog","b"=>"Cat");
$a=array("b"=>"Cat","a"=>"Dog","c"=>"Horse");

thetestingsite
03-02-2007, 03:40 AM
I have the following array

$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.

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).


$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.