PHP Array Exercises : Change the array values to upper or lower case
PHP Array: Exercise-12 with Solution
Write a PHP function to change the following array's all values to upper or lower case.
Sample arrays :
$Color = array('A' => 'Blue', 'B' => 'Green', 'c' => 'Red');
Sample Solution:
PHP Code:
<?php
// Define a function named 'array_change_value_case' that changes the case of array values
function array_change_value_case($input, $ucase)
{
// Store the desired case (CASE_UPPER or CASE_LOWER) in the variable $case
$case = $ucase;
// Initialize an empty array to store the new values
$narray = array();
// Check if the input is not an array
if (!is_array($input))
{
// If not an array, return an empty array
return $narray;
}
// Iterate through the input array
foreach ($input as $key => $value)
{
// Check if the current value is an array
if (is_array($value))
{
// If it's an array, recursively call the function on the sub-array
$narray[$key] = array_change_value_case($value, $case);
// Continue to the next iteration
continue;
}
// Change the case of the current value based on the specified case
$narray[$key] = ($case == CASE_UPPER ? strtoupper($value) : strtolower($value));
}
// Return the new array with changed case values
return $narray;
}
// Define an associative array $Color with keys 'A', 'B', and 'c'
$Color = array('A' => 'Blue', 'B' => 'Green', 'c' => 'Red');
// Output a message indicating the start of the section for the actual array
echo 'Actual array ';
// Display the original array $Color
print_r($Color);
// Output a message indicating that values are in lower case
echo 'Values are in lower case.';
// Call the array_change_value_case function with CASE_LOWER and display the result
$myColor = array_change_value_case($Color, CASE_LOWER);
print_r($myColor);
// Output a message indicating that values are in upper case
echo 'Values are in upper case.';
// Call the array_change_value_case function with CASE_UPPER and display the result
$myColor = array_change_value_case($Color, CASE_UPPER);
print_r($myColor);
?>
Output:
Actual array Array ( [A] => Blue [B] => Green [c] => Red ) Values are in lower case.Array ( [A] => blue [B] => green [c] => red ) Values are in upper case.Array ( [A] => BLUE [B] => GREEN [c] => RED )
Flowchart:
PHP Code Editor:
Contribute your code and comments through Disqus.
Previous: Write a PHP program to merge (by index) the specified two arrays.
Next: Write a PHP script which displays all the numbers between 200 and 250 that are divisible by 4.
What is the difficulty level of this exercise?
Test your Programming skills with w3resource's quiz.
It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.
https://w3resource.com/php-exercises/php-array-exercise-12.php
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics