I've done some searching and have found similar questions but most of them have string keys and not numerical. Basically this is what I would like to achieve:
Sample Array
Array (
[0] => comments=DISABLED
[1] => img_carousel=red.jpg,yellow.png,blue.jpg
[2] => twitter=http://www.twitter.com
)
Running something like this:
$img_carousel = explode('=', $arr[array_search('img_carousel', $arr)]);
will return:
Array (
[0] => img_carousel
[1] => red.jpg,yellow.png,blue.jpg
)
However, it does not and only returns 0/FALSE. I'm guessing it is because array_search searches for an exact match and not for a keyword within a string?
I tried to use preg_grep, unfortunately, I just can't seem to understand regex and searching for a literal string has proven to be too difficult for me... :{
You want something like this:
$img_carousel = explode('=', array_shift(preg_grep('/img_carousel=/', $arr)))
As of php 5.3 you could follow this sample:
$result = array_filter($arr, function($e) {
return strpos($e, 'img_carousel') !== false;
});
or if you use old versions:
function ifElementContainsImgCarousel($e)
{
return strpos($e, 'img_carousel') !== false;
}
$result = array_filter($arr, 'ifElementContainsImgCarousel');
You can use array_filter
to get the elements which contains your keyword.
array_filter($sample_array, function($var) use ($keyword) {return strpos($var, $keyword) !== false;})