1

I am working on an import script that needs to evaluate whether the set string fits with the possible values the backend field can have. More exactly what I have is this array of committes:

$committees = array(
    'Ämter'         => 1,
    'Abteilungen'   => 2,
    'Konservatoren'     => 3,
    'Dienstagssitzung'  => 4,
);

and now I need to figure out if a string saved in variable $category matches any key in that array. If it does match one of the entries, I need it to return the value (1, 2, 3 or 4) that goes with that key.

I read up about it here on Stackoverflow and found plenty examples to see if a value equals one in an array, for example: preg_match array items in string? and tried to follow those along. I tried

$committeesKeys = '/(' . implode('|', array_keys($committees)) . ')/';
$matches = preg_match($committeesKeys, $category);

but that only returned how many matches it found?

I also tried

$input = preg_quote($category, '/');
$matches = preg_filter('/'.$input.'/', null, $committees);

as that was suggested somehwere else, can't find the link anymore, but that returned an empty array.

I am new to all of this so might be totally wrong here.

Can anybody tell me how I can do this, or where I can find an answer to the question? I might just not have found it, my brain is rather tired right now...

Community
  • 1
  • 1
deadfishli
  • 729
  • 5
  • 17

4 Answers4

3

you can do something like this:

function getValue($category){
    if (array_key_exists($category, $committees)){
       return $committees[$category]; //the value you want
    }
}

Hope this helps :)

William J.
  • 1,574
  • 15
  • 26
2

I feel that I have right to post that as answer accepted :-) :

echo (isset($committees[$category]))?$committees[$category]:'There is no '.$category.' category';

Alex
  • 16,739
  • 1
  • 28
  • 51
0

preg_match() has a 3rd argument which will allow you to save capture groups into a numerical array. However, if you want to compare a string directly you can simply use a loop and strcmp or === which will probably work faster since preg_match has to compile the regex you define in the first argument. My solution for this problem would look like:

$found = FALSE;
foreach ( $committees as $name=>$number ) {
    if ( $name === $category ) {
        $found = $number;
    }
}
return $found;
0

You make it difficult by not showing what is in the category matches.

Maybe something like this.

$results = array_intersect ($matches,$committees );
Misunderstood
  • 5,534
  • 1
  • 18
  • 25