I need to make a function that reads my variables at the top and fixes the string so that each word in it has a capital letter. The way I'm currently doing it doesn't seem to work. Here is what I have:
<?php
$course1 = "advanced web development";
$course2 = "mobile app development";
$course3 = "info systems with business intell";
function fixCourseName($courseName) {
$courseName = ucwords($courseName);
}
fixCourseName($course1);
echo $course1;
?>
Does anyone know what would be causing the output to still be lower case?
You can either pass it by reference, by using the & operator in front of the variable when passing it as an argument. This will change the variable you pass through, without having to return it. The variable is then changed in the global scope.
function fixCourseName(&$courseName) {
$courseName = ucwords($courseName);
}
fixCourseName($course1);
echo $course1;
You can also return the new value, but then it must be assigned again.
function fixCourseName($courseName) {
return ucwords($courseName);
}
$course1 = fixCourseName($course1);
echo $course1;
The better solution, if the fixCourseName() function does nothing more than using ucwords(), you might as well just use
$course1 = ucwords($course1);
echo $course1;
See this live demo to see it all in action.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With