-1

I have the following text string: "Gardening,Landscaping,Football,3D Modelling"

I need PHP to pick out the string before the phrase, "Football".

So, no matter the size of the array, the code will always scan for the phrase 'Football' and retrieve the text immediately before it.

Here is my (lame) attempt so far:

$array = "Swimming,Astronomy,Gardening,Rugby,Landscaping,Football,3D Modelling";
$find = "Football";
$string = magicFunction($find, $array);
echo $string; // $string would = 'Landscaping'

Any help with this would be greatly appreciated.

Many thanks

michaelmcgurk
  • 6,367
  • 23
  • 94
  • 190

3 Answers3

2
//PHP 5.4
echo explode(',Football', $array)[0]

//PHP 5.3-
list($string) = explode(',Football', $array);
echo $string;
Explosion Pills
  • 188,624
  • 52
  • 326
  • 405
  • Thanks for this. However, it doesn't remove the content **BEFORE** the phrase 'Football'. So, my $string becomes `Swimming,Astronomy,Gardening,Rugby,Landscaping`. Any ideas? Thank you. – michaelmcgurk Dec 18 '12 at 16:51
  • 1
    Oh, by "pick out" I thought you meant "get" not "remove." Just use `[1]` or `list(,$string)`. – Explosion Pills Dec 18 '12 at 16:52
2
$terms = explode(',', $array);
$index = array_search('Football', $terms);
$indexBefore = $index - 1;

if (!isset($terms[$indexBefore])) {
    trigger_error('No element BEFORE');
} else {
    echo $terms[$indexBefore];
}
deceze
  • 510,633
  • 85
  • 743
  • 889
1
$array = array("Swimming","Astronomy","Gardening","Rugby","Landscaping","Football","3D" "Modelling");
$find = "Football";
$string = getFromOffset($find, $array);
echo $string; // $string would = 'Landscaping'

function getFromOffset($find, $array, $offset = -1)
{
    $id = array_search($find, $array);
    if (!$id)
        return $find.' not found';
    if (isset($array[$id + $offset]))
        return $array[$id + $offset];
    return $find.' is first in array';
}

You can also set the offset to be different from 1 previous.

qooplmao
  • 17,622
  • 2
  • 44
  • 69