-1

I have a string like so:

Quaint village location, seaside views, four bedrooms

I need to do the following:

  • Take each comma separated item and add it into an array
  • Remove whitespace from beginning and end
  • Capitalise the first letter

So for example, the above string becomes:

array(
   [0] => 'Quaint village location',
   [1] => 'Seaside views',
   [2] => 'Four bedrooms',
)

I have started this code block using trim, explode and ucfirst but I don't think I'm going about it a very efficient way.

iif(get_field('property_information') != NULL){
        $raw_facilities_list = explode(",", get_field('property_information'));
        $other_facilities_list = [];
        foreach($raw_facilities_list as $facility){
            $facility = trim($facility);
            $facility = ucfirst($facility);
            array_push($other_facilities_list,$facility);
        }
        $property['extra_features'] = $other_facilities_list;
        echo '<pre>';
            var_dump($property);
        echo '</pre>';
    }

What is the most efficient way to perform these 3 tasks?

Francesca
  • 26,842
  • 28
  • 90
  • 153

2 Answers2

2

Simply using array_map along with explode

$property['extra_features'] = array_map(function($v){
  return ucfirst(trim($v));
},explode(',',$str));

Output:

array(
   [0] => 'Quaint village location',
   [1] => 'Seaside views',
   [2] => 'Four bedrooms',
)

Demo

Narendrasingh Sisodia
  • 21,247
  • 6
  • 47
  • 54
0

You're doing it right; you could split it up into some parts, though:

function sanitize($string){
    return ucfirst(trim($string));
}

function treat($sentence)
{
    return join(",",(array_map('sanitize',explode(",",$sentence))));
}


$array[] = treat("Quaint village location, seaside views, four bedrooms");
rdiz
  • 6,136
  • 1
  • 29
  • 41