Reputation: 1
Im trying to retrieve an array of images. All images are appearing fine. However,images with name "image_01" and "image_02" are being retrieved as image_1 and image_2. It is because of the "str_replace" Im using. Can someone tell me why this is happening?
$image=$policy->gallery;
$image = trim($image,'*');
$temp = explode('*',$image );
echo $temp[5];
// $temp = array_filter($temp);
foreach($temp as $image)
{
$images[]=base_url()."images/park_photos/".trim( str_replace( array('['*']') ,"" ,$image ) );
//echo trim( str_replace( array('['*']') ,"" ,$image ));
}
foreach($images as $image)
{
echo "<img src='{$image}' style='width:100px; height:100px; display:block; float:left;' />";
}
?>
Upvotes: 0
Views: 64
Reputation: 3748
In order to fix it, you need to replace
$images[]=base_url()."images/park_photos/".trim( str_replace( array('['*']') ,"" ,$image ) );
with
$images[] = base_url() . trim($image);
or even with
$images[] = base_url() . $image;
What's happening? I guess that with this str_replace
you wanted to make sure that *
is removed from picture name. But you did it before already ($temp = explode('*',$image );
) so no need to duplicate.
Now, why does 0
get removed from picture name? There's some "magic" happening in array('['*']')
. The *
character is interpreted as multiplication, because of the quotation marks sequence. To understand, try doing this:
$a = '['*']';
var_dump($a);
// outputs: int(0)
Why? PHP is guessing variables types from context. The context in this case is: multiply '['
by ']'
. Since multiplication applies to numbers, PHP casts the two strings ('['
and ']'
) to integers, zeros specifically. (Read more about Type Juggling).
So, str_replace( array('['*']') ,"" ,$image )
equals str_replace( array(0) ,"" ,$image )
- that is "replace zeros with empty string.
Upvotes: 2