2
stdClass Object ( [id] => 11 [type] => 5 [color_a] => 57 [color_b] => 3 [date] => 2 )

How to check if the object has attributes that CONTAIN the string "color" ?

I tried with array_diff_key and array_filter but i cannot use ARRAY_FILTER_USE_KEY because it runs on PHP 5.4.

No loops if possible :)

Mike
  • 5,416
  • 4
  • 40
  • 73
  • possible duplication: http://stackoverflow.com/questions/2471120/php-function-array-key-exists-and-regular-expressions – YyYo Apr 01 '15 at 17:39

3 Answers3

2

This should work for you:

(Here I just cast the object to an array and search with preg_grep() in the array_keys(). Then I simply flip the array back with array_flip())

$result = array_flip(preg_grep("/\bcolor/", array_keys((array)$o)));
print_r($result);

output:

Array ( [color_a] => 2 [color_b] => 3 )

And if you just want to use it to check for TRUE or FALSE like with in_array() you don't need to flip it back and you can simply use it like this:

if(preg_grep("/\bcolor/", array_keys((array)$o)))
    echo "match";
Rizier123
  • 58,877
  • 16
  • 101
  • 156
0
function isKeyExists($key,$array){
    $arr = preg_grep('/.*'.$key.'.*/',array_keys($array));
    if(count($arr)){
        return true;
    }  
    return false;
}
$arr = Array('id'=>'11','type'=>5,'color_a'=>57,'color_b'=>3,'date'=>2);
isKeyExists('color_',$arr); // return boolean if exists or not
mickmackusa
  • 43,625
  • 12
  • 83
  • 136
YyYo
  • 651
  • 5
  • 13
0

No regex solution:

    $std          = new StdClass();
    $std->id      = 11;
    $std->type    = 5;
    $std->color_a = 57;
    $std->color_b = 3;
    $std->date    = 2;

    $result    = array();
    $searchFor = 'color';

    array_map(function($value) use(&$result, $searchFor){

        if(strpos($value, $searchFor) !== false){
            $result[] = $value;
        }

    }, array_keys((array)$std));

    var_dump(count($result));
Alex Kalmikov
  • 1,865
  • 19
  • 20