简体   繁体   中英

Check associative string array values

I have the following string array

$array = array(
    "key" => "zhcdde,hzccd,eezhg"
);

I want to get the values, split them with ',' and count the equal letters. For example only "z" and "h" are equal, since these are the only characters that occur in every string composition. I tried a few things like this

$equalLetters = 0;
foreach ($array as $key => $splitWords) {
    $words = explode(",", $splitWords);
    for ($letter = 0; $letter < strlen($words[0]); $letter++) {
        if ($words[0][$letter] == $words[1][$letter] || $words[0][$letter] == $words[2][$letter] || $words[1][$letter] == $words[2][$letter]) {
            $equalLetters++;
        }
    }
}
echo $equalLetters;

Without success. Can you guys help me ?

Unclear for me how the associative array factors into it, but here's how you can get the common letters in your strings:

<?php
    $string = 'zhcdde,hzccd,eezhg';
    $words = explode(',', $string);
    $letters = array_map('str_split', $words);
    $common = call_user_func_array('array_intersect', $letters);

    var_dump($common);
?>

Which outputs:

array(2) {
  [0]=>
  string(1) "z"
  [1]=>
  string(1) "h"
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM