Saturday, November 16, 2024
Google search engine
HomeLanguagesPHP | Change strings in an array to uppercase

PHP | Change strings in an array to uppercase

You are given an array of strings. You have to change all of the strings present in the given array to uppercase no matter in which case they are currently. Print the resultant array. Examples:

Input : arr[] = ("neveropen", "For", "GEEks")
Output : Array ([0]=>GEEKS [1]=>FOR [2]=>GEEKS)

Input :  arr[] = ("neveropen")
Output : Array ([0]=>GEEKS)

To solve this problem one of the basic approach is to iterate over all string of input array and then change them to uppercase one by one and print them. Iterating over array makes a quite use of for loop in program which can be avoided by using some smart methods like array_change_key_case() and array_flip(). What we have to do is just flip the array keys to value and vice-versa after that change the case of new keys of array which actually changes the case of original strings value and then again flip the key and values by array_flip(). Below is the step by step process:

  1. use array_flip() function swap keys with the values present in the array. That is, the keys will now become values and their respective values will be their new keys.
  2. use array_change_key_case() function to change case of current keys(original values).
  3. use array_flip() function again to flip key and values of array to obtain original array where strings value are in upper case.

Below is the implementation of above approach in PHP: 

PHP




<?php
 
// Program to change strings in an array to upper case
 
$input = array("Practice", "ON", "GeeKs", "is best");
 
// print array before conversion of string
print"Array before string conversion:\n";
print_r($input);
 
// Step 1: flip array key => value
$input = array_flip($input);
 
// Step 2: change case of new keys to upper
$input = array_change_key_case($input, CASE_UPPER);
 
// Step 3: reverse the flip process to
// regain strings as value
$input = array_flip($input);
 
// print array after conversion of string
print"\nArray after string conversion:\n";
print_r($input);
 
?>


Output :

Array before string conversion:
Array
(
    [0] => Practice
    [1] => ON
    [2] => GeeKs
    [3] => is best
)

Array after string conversion:
Array
(
    [0] => PRACTICE
    [1] => ON
    [2] => GEEKS
    [3] => IS BEST
)

RELATED ARTICLES

Most Popular

Recent Comments