-1

I have an array containing integers and letters and I need to remove the integers and form a string which is all lowercase except the first letter.

$chars = ["A", 1, 2, "h", "m", "E", "D"];

//Needed Output is: Ahmed

My attempt:

foreach ($chars as $char) {
  if (gettype($char) == "string") {
    echo strtolower($char);
  }
}
The Output is:

ahmed

but I don't how to make the first letter Capital, Is there any function that can do that with arrays?

mickmackusa
  • 43,625
  • 12
  • 83
  • 136

2 Answers2

0

Short answer - there is an ucfirst function, but it only works on string not arrays

So we need to prepare a little bit. You can use implode to convert the array and glue it with an empty seperator.

ucfirst will convert only the first letter to Capital, so we need to make sure that the other letters are lowercase; we can use strtolower function to achieve that.

And finally - I would use an array_filter for that foreach in your code

function testChar($char) {
    return gettype($char) === "string";
}

$chars = ["A", 1, 2, "h", "m", "E", "D"];
$result = array_filter($chars, "testChar");
$stringResult = implode("", $result);
$toLowerstringResult = strtolower($stringResult);
$ucfirstResult = ucfirst($toLowerstringResult);
echo $ucfirstResult;
Karol Oracz
  • 182
  • 6
angel.bonev
  • 2,154
  • 3
  • 20
  • 30
0
  1. Filter out non-string type elements.
  2. Convert the array to a string.
  3. Force all letters to lowercase except the first which must be uppercase.

Code: (Demo)

echo mb_convert_case(
         implode(
             array_filter(
                 $chars,
                 'is_string'
             )
         ),
         MB_CASE_TITLE
     );
mickmackusa
  • 43,625
  • 12
  • 83
  • 136