Let's say I have input string
String 1 : 1234123
String 2 : 76523752
From those string, I'd like to know which numbers that only appears once. So in my case the output should be
String 1 : array(4)
String 2 : array(6,3)
I'm guessing I'll use strpos()
for this task but I couldn't get any logical flow to make this happen. Can you help me figure this out?
Boring solution but it works!
$string="1234123";
$result=array();
foreach (count_chars($string, 1) as $i => $val) {
if($val==1) $result[]=chr($i);
}
print_r($result);
The solution using array_keys
, array_filter
, array_count_values
and str_split
functions:
$strings = [
'String 1' => '1234123',
'String 2' => '76523752'
];
$result = [];
foreach ($strings as $k => $v) {
$result[$k] = array_keys(array_filter(array_count_values(str_split($v)), function($v){
return $v == 1;
}));
}
print_r($result);
The output:
Array
(
[String 1] => Array
(
[0] => 4
)
[String 2] => Array
(
[0] => 6
[1] => 3
)
)
As an alternative:
$string = "1235235236";
$res=[];
foreach(str_split($string) as $c) $res[$c]++;
$res = array_filter($res, function($a){return $a == 1;});
var_dump($res);