I have this kind of array, i will make it very simple to understand
$picture = ( 'artist2-1_thumb.jpg',
'artist2-2.jpg' ,
'artist2-3_thumb.jpg',
'artist2-4.jpg',
'artist2-5_thumb.jpg');
Now i want use substr to get new array that only have thumb, to have new array like this
$picturethumbs = ( 'artist2-1_thumb.jpg',
'artist2-3_thumb.jpg',
'artist2-5_thumb.jpg');
Can some substr but where to start?
You could use array_filter()
to filter the array, returning only items which match the given condition:
$picturethumbs = array_filter($picture, function($v) {
return strpos($v, '_thumb') !== false;
});
Would return all array items which contain the string _thumb
. This could be useful if you don't know the extension of the file, or if _thumb
appears somewhere other than the end of the string (eg. my_thumb.gif
would still match)
$picturethumbs = array_filter($picture, function($v) {
return substr($v, -10) === '_thumb.jpg';
});
Would return all array items where the last 10 characters match _thumb.jpg
.
Both (given your example array) output:
array
0 => string 'artist2-1_thumb.jpg' (length=19)
2 => string 'artist2-3_thumb.jpg' (length=19)
4 => string 'artist2-5_thumb.jpg' (length=19)
Here you are:
$picturethumbs = array();
foreach ($picture as $val) {
if (substr($val, -10) == '_thumb.jpg') {
$picturethumbs[] = $val;
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With