ntgCleaner
ntgCleaner

Reputation: 5985

PHP Get first array value that ends with ".jpg"

I have some arrays and they might all be formatted like so:

Array (
    [0] => .
    [1] => ..
    [2] => 151108-some_image-006.jpg
    [3] => high
    [4] => low
)

I know they have 5 values, but I can not be certain where each value is being placed.

I am trying to get only the image out of this array

$pos = array_search('*.jpg', $main_photo_directory);
echo $main_photo_directory[$pos];

But as we all know, it's looking for a literal *.jpg which it can't find. I'm not so super at regex and wouldn't know how to format an appropriate string.

What is the best way to get the first image (assuming there may be more than one) out of this array?

ADDITION

One of the reasons I am asking is to find a simple way to search through an array. I do not know regex, though I'd like to use it. I wrote the question looking for a regex to find '.jpg' at the end of a string which no search results had yielded.

Upvotes: 0

Views: 390

Answers (2)

Leah Zorychta
Leah Zorychta

Reputation: 13429

You can loop over the array until you find a string ending in jpg:

function endsWith($haystack, $needle) {
    return $needle === "" || (($temp = strlen($haystack) - strlen($needle)) >= 0 && strpos($haystack, $needle, $temp) !== FALSE);
}

$array = [];
$result = false;
foreach($array as $img) {
  if(endsWith($img, '.jpg')) {
    $result = $img;
    break;
  }
}

echo $result;

Upvotes: 0

AbraCadaver
AbraCadaver

Reputation: 78994

This should work:

echo current(preg_grep('/\.jpg$/', $array));

Upvotes: 7

Related Questions