phparraysfilteringimplodetitle-case

Convert array of mixed type elements to title-cased string


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?


Solution

  • 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;