Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Running "strpos" on each array element

Tags:

arrays

php

I need to find out if a string exists within an array value, but isn't necessarily the actual array value.

$array = array(
       0 => 'blue', 
       1 => 'red', 
       2 => 'green', 
       3 => 'red'
);

$key = xxxxxx('gr', $array); // $key = 2;

Is there a built in way to do this with PHP

like image 201
Webnet Avatar asked May 03 '11 13:05

Webnet


2 Answers

You can use preg_grep for this purpose

<?php
$array = array(
       0 => 'blue', 
       1 => 'red', 
       2 => 'green', 
       3 => 'red'
);

//$key = xxxxxx('gr', $array); // $key = 2;
$result=preg_grep("/^gr.*/", $array);
print_r($result);
?>

DEMO

like image 114
Shakti Singh Avatar answered Nov 11 '22 13:11

Shakti Singh


Function: array_filter is what you want. It will only preserve the items in the resulting array when the specified function return true for them.

// return true if "gr"  found in $elem
// for this value
function isGr($key, $elem)
{
    if (strpos($elem, "gr") === FALSE)
    {
         return FALSE;
    }
    else
    {
         return TRUE;
    }
}

$grElems = array_filter($array, "isGr");
print_r($grElems);

results in:

array(
    2=>'green'
)
like image 43
Doug T. Avatar answered Nov 11 '22 13:11

Doug T.