Search code examples
phplaravelcollections

Check if the character exists in the collection laravel


I have a CSV file with zip codes. Some cities have only one zip code whereas some have multiple zip codes.

istat;municipality;region;province_abbreviation;province;zip_code_check;zip_code;lat;lng
60006;Anagni;Lazio;FR;Frosinone;"03012";"03012";41.74393633;13.15452041
67002;Ancarano;Abruzzo;TE;Teramo;64010;64010;42.83680898;13.74139609
42002;Ancona;Marche;AN;Ancona;60121-60131;60121;43.61675973;13.51887537
42002;Ancona;Marche;AN;Ancona;60121-60131;60122;43.61675973;13.51887537
42002;Ancona;Marche;AN;Ancona;60121-60131;60123;43.61675973;13.51887537
42002;Ancona;Marche;AN;Ancona;60121-60131;60124;43.61675973;13.51887537
42002;Ancona;Marche;AN;Ancona;60121-60131;60125;43.61675973;13.51887537
42002;Ancona;Marche;AN;Ancona;60121-60131;60126;43.61675973;13.51887537
42002;Ancona;Marche;AN;Ancona;60121-60131;60127;43.61675973;13.51887537
42002;Ancona;Marche;AN;Ancona;60121-60131;60128;43.61675973;13.51887537
42002;Ancona;Marche;AN;Ancona;60121-60131;60129;43.61675973;13.51887537
42002;Ancona;Marche;AN;Ancona;60121-60131;60131;43.61675973;13.51887537

I am getting these in the $collection I want to extract the row which has - in the zip_code_check column. I tried $collection->where('zip_code_check', 'like'. '%-%') but it did not work. Is there any way I can get rows when the column zip_code_check has -?


Solution

  • I used str_contains but it returned a boolean instead of a filtered row. Here is how I fixed my problem.

    $filter = $collection->filter(function($value, $key) {
    if (str_contains($value['zip_code_check'], '-')) {
            return $value;
         }
    });