0

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.

ntgCleaner
  • 5,865
  • 9
  • 48
  • 86

2 Answers2

7

This should work:

echo current(preg_grep('/\.jpg$/', $array));
AbraCadaver
  • 78,200
  • 7
  • 66
  • 87
  • Cleanest, simplest, most straight forward answer. Thank you. - Will accept in 7 minutes – ntgCleaner Nov 17 '15 at 20:11
  • Indeed, impressive. You only have to take care how to use the result, since you cannot simply use `current()` in function calls, for example. – arkascha Nov 17 '15 at 20:14
  • @arkascha That's fine, I am using the literal string to push back through an ajax call. What has been supplied works perfectly for my needs. – ntgCleaner Nov 17 '15 at 20:17
  • @arkascha: What? Why not? `echo strtoupper(current(preg_grep('/\.jpg$/', $array)));` – AbraCadaver Nov 17 '15 at 20:19
0

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;
David Zorychta
  • 13,039
  • 6
  • 45
  • 81