Reputation: 635
I want to count all the values (The name of the cities) in this array who have the character t before the last character in the string.
ARRAY
$cities_array = array(
"city1" => "Paris_t1",
"city2" => "Madrid_t1",
"city3" => "Amsterdam_t1",
"city4" => "London_i1",
"city5" => "Miami_i1",
"city6" => "Berlin_i1",
"city7" => "Brussels_i1",
"city8" => "Toronto_i1",
);
The results should be: 3 (Paris_t1 - Madrid_t1 - Amsterdam_t1)
I believe i have to combine:
array_count_values($cities_array)
and
substr($value, -2, 1) == "t"
I have tried, but I get only errors.
Upvotes: 0
Views: 51
Reputation: 7896
Try below solution:
$cities_array = array(
"city1" => "Paris_t1",
"city2" => "Madrid_t1",
"city3" => "Amsterdam_t1",
"city4" => "London_i1",
"city5" => "Miami_i1",
"city6" => "Berlin_i1",
"city7" => "Brussels_i1",
"city8" => "Toronto_i1",
);
$filtered_array = array_filter($cities_array, function($val){
return (strpos($val, 't', (strlen($val)-2)) !== false);
});
print_r($filtered_array);
output: - (you can implode array by - to get desired result)
Array
(
[city1] => Paris_t1
[city2] => Madrid_t1
[city3] => Amsterdam_t1
)
In above solution in strpos
third parameter strlen($val)-2)
i.e. position will be searched from second last character of $val
Upvotes: 0
Reputation: 407
This will give you what you want.
$cities_array = array(
"city1" => "Paris_t1",
"city2" => "Madrid_t1",
"city3" => "Amsterdam_t1",
"city4" => "London_i1",
"city5" => "Miami_i1",
"city6" => "Berlin_i1",
"city7" => "Brussels_i1",
"city8" => "Toronto_i1",
);
$count = 0;
$city_text = '';
foreach($cities_array as $city){
if(substr($city, -2, 1) == "t"){
$count++;
$city_text .= $city . '-';
}
}
echo $count. "(".rtrim($city_text,'-').")";
Upvotes: 2