Converting array values into Sentence cases

I have an array and i want the values in the arrays to be in Sentence cases formats like School, Church, Hospital.

Eg:

$arr = array('school', 'chURch', 'HOSpitaL');
$i = 0;

foreach($arr as $a){
  $newarr[] = ucfirst(strtolower($arr[$i]));
   $i++;
}

But the above code only makes school to be School, but leaves others unchanged, i first converted all values to lowercase and then try to make the first letters of each value to be Capitalized.

Please any way of archiving this?

<?php

$arr = array('school', 'chURch', 'HOSpitaL');

foreach($arr as $a){
    $newarr[] = ucfirst(strtolower($a));
}

print_r($newarr);
2 Likes

Your posted code does work. If it didn’t, that’s not the code that was running.

Alternate method -

$arr = array('school', 'chURch', 'HOSpitaL');

$arr = array_map('strtolower',$arr);
$arr = array_map('ucfirst',$arr);

print_r($arr);
2 Likes

In a foreach loop you don’t need the $i and $i++.
A foreach loop iterates through an array without you needing to increase anything ech iteration.

maybe a variable is overriding it, i will figure it out, and Also i learnt not to use $i using the example @benanamen posted.

Also i learnt to use array_map() which is alot easier and shorter.

Thanks everyone.

1 Like

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.