You will need to collect the right side values as you loop through them and check for duplicates. I am accessing the strings' right side values via their "offset" [2]
. When found, you can exit the loop with a break
.
Code: (Demo)
$array=['1%2','3%4','1%2','1%3'];
$kept=[];
foreach($array as $i=>$v){
if(in_array($v[2],$kept)){
echo "Element (index $i) containing $v has duplicate right side value.";
break;
}
$kept[]=$v[2];
}
Output:
Element (index 2) containing 1%2 has duplicate right side value.
If you want to search for all element that end with %2
, you can use preg_grep()
.
Code:
$search=2;
$array=['1%2','1%3','1%4','3%2','5%2'];
var_export(preg_grep("/%{$search}$/",$array));
Output:
array (
0 => '1%2',
3 => '3%2',
4 => '5%2',
)
Or without regex, it will require more function calls:
$search=2;
$array=['21%2','1%3','2%22','1%4','3%21','5%2'];
var_export(array_filter($array,function($v)use($search){return strpos($v,"%$search")+2===strlen($v);}));
Output:
array (
0 => '21%2',
5 => '5%2',
)
...[deep breath] Here is attempted answer #4...
Code:
$array=['1%2','1%3','1%4','3%2','5%2'];
foreach($array as $v){
$grouped[explode('%',$v)[1]][]=$v; // use right side number as key
}
var_export($grouped);
Output:
array (
2 =>
array (
0 => '1%2',
1 => '3%2',
2 => '5%2',
),
3 =>
array (
0 => '1%3',
),
4 =>
array (
0 => '1%4',
),
)
If you want to count the right side values in the array:
$array=['1%2','1%3','1%4','3%2','5%2'];
$array=preg_replace('/\d+%/','',$array); // strip the left-size and % from elements
var_export(array_count_values($array)); // count occurrences
Output:
// [right side values] => [counts]
array (
2 => 3,
3 => 1,
4 => 1,
)