Shoe
Shoe

Reputation: 76240

Foreach loop problem

I have an array as follows

$posts = array(
    0 => array('user' => 'Charlie', 'message' => 'First message'),
    1 => array('user' => 'Charlie', 'message' => 'Second message'),
    2 => array('user' => 'Charlie', 'message' => 'Third message TEXT!'),
    3 => array('user' => 'Charlie', 'message' => 'Fourth message')
);

and I'd like to replace "TEXT" with "NEXT" if it's inside the message. How could i do this?

I tried with

foreach ($posts as $r)
{
    $r['message'] = str_replace('TEXT', 'NEXT', $r['message']);
}

But seems not to be working.

Upvotes: 0

Views: 222

Answers (5)

stealthyninja
stealthyninja

Reputation: 10371

@Charlie Pigarelli: Try --

for ($i = 0; $i < count($posts); $i++)
{
    $posts[$i]['message'] = str_replace('TEXT', 'NEXT', $posts[$i]['message']);
}

Upvotes: 1

Luca Filosofi
Luca Filosofi

Reputation: 31173

 foreach ($posts as $key => $r)
{
    $posts[$key]['message'] = str_replace('TEXT', 'NEXT', $r['message']);
}

Upvotes: 2

GolezTrol
GolezTrol

Reputation: 116100

foreach ($posts as &$r)
{
    $r['message'] = str_replace('TEXT', 'NEXT', $r['message']);
}

The & will cause $r to be a reference to the value which allows you to change it inside the original array. In your code, you're modifying a copy.

Upvotes: 2

soju
soju

Reputation: 25312

foreach ($posts as &$r)
{
    $r['message'] = str_replace('TEXT', 'NEXT', $r['message']);
}

Upvotes: 3

lonesomeday
lonesomeday

Reputation: 237847

That's because foreach by default uses a copy of the array elements, rather than the elements themselves. You can use & to change this to a reference:

foreach ($posts as &$r) {

Upvotes: 5

Related Questions