This question already has an answer here:
I am doing a program where my input is "palash". Output will be:
p-1
a-2
l-1
s-1
h-1
My code is given below:
<?php
$myString="palash";
$j=strlen($myString);
$narray = array();
for($i=0;$i<$j;$i++){
$val = 0;
for($k=0;$k<$j;$k++){
if($myString[$i]==$myString[$k]){
$val++;
}
}
$key = $myString[$i];
$narray[$key] = $val;
}
foreach($narray as $key => $val){
echo $key. "-". $val;
echo"<br>";
}
?>
But i want minimize my code and want to add a search option before 2nd loop to search whether the item is duplicate or not. So that i can eliminate my second foreach loop.
</div>
You can use array_count_values
to count the values. You can check if there is duplicate when there are 2 or more values.
$myString = "palash";
$arr = str_split( $myString ); //Split the string into array.
$arr = array_count_values( $arr ); //Count the array values.
echo "<pre>";
print_r( $arr );
echo "</pre>";
This will result to:
Array
(
[p] => 1
[a] => 2
[l] => 1
[s] => 1
[h] => 1
)
Doc: array_count_values()
You can check if array key exists, then increment the counter
<?php
$myString="palash";
$j=strlen($myString);
$narray = array();
for($i=0;$i<$j;$i++){
$key = $myString[$i];
if(array_key_exists($key,$narray))
{
$narray[$key] = $narray[$key]+1;
}
else
{
$narray[$key] = 1;
}
}
foreach($narray as $key => $val){
echo $key. "-". $val;
echo"<br>";
}
?>