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 mes开发者_如何学运维sage 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.
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) {
foreach ($posts as &$r)
{
$r['message'] = str_replace('TEXT', 'NEXT', $r['message']);
}
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.
foreach ($posts as $key => $r)
{
$posts[$key]['message'] = str_replace('TEXT', 'NEXT', $r['message']);
}
@Charlie Pigarelli: Try --
for ($i = 0; $i < count($posts); $i++)
{
$posts[$i]['message'] = str_replace('TEXT', 'NEXT', $posts[$i]['message']);
}
精彩评论