Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
242 views
in Technique[技术] by (71.8m points)

php - Is there a way to reformat an array when echoing the foreach loop?

I am new to PHP and I have an array and I would like to echo, but formatted so that the country names are written in the proper cases with the first letter capitalized.

For example:

cAnAdA echos as Canada (Cap C)

SwitZerLand echos as Switzerland (Cap S)

I know strtoupper(); all uppercase, strtolower(); all lowercase and ucfirst(); capitalize the first letter, but I want all the cases converted to lowercase and then the first letter capitalized.

Below is my code with the array and foreach loop.

<?php

$countries = [
    'cAnAdA',
    'SwitZerLand',
    'GrEEce',
    'HUnGary',
    'CroATia',
    'IndOneSia',
    'IrElAnd',
    'InDia',
    'MonGoLia',
    'UNitED StaTes of AmeriCA',
    'ChiNa',
    'romaNia',
    'Poland',
    'SieRRA LeoNe',
    'fraNcE',
    'JaPAn',
    'Belgium',
    'TuRkEy',
    'Aland islANds',
    'YeMen',
    'Egypt',
];


foreach($countries as $country){

 echo strtoupper($country);
}

Thank you in advance!!

question from:https://stackoverflow.com/questions/65866126/is-there-a-way-to-reformat-an-array-when-echoing-the-foreach-loop

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)
foreach($countries as $country){
    echo ucwords(strtolower($country))
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...