4

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?

2 Answers 2

8

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's a demo

Sign up to request clarification or add additional context in comments.

3 Comments

@Legionar I've updated it, thanks for pointing that out (it would have worked that way anyway, better to be explicit though)
But what if '_thumb' will be f.e. at the beginning of the string? In the title is "Substr from end of string", but your answer will choose it also if its not only at the end of the string...
@Legionar then it would have found it. I presumed the OP wanted to get an array of all items which contained _thumb
1

Here you are:

$picturethumbs = array();

foreach ($picture as $val) {
  if (substr($val, -10) == '_thumb.jpg') {
    $picturethumbs[] = $val;
  }
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.