Reputation: 59
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?
Upvotes: 3
Views: 127
Reputation: 26450
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.
Upvotes: 2
Reputation: 310983
Your function gets a copy of the string passed to it and then updates it. If you want to it affect the original variable that's passed to it, you need to pass it by reference, by adding a &
:
function fixCourseName(&$courseName) {
# Here ------------^
$courseName = ucwords($courseName);
}
If your function is just calling ucwords
, you don't really need it - just call ucwords
directly:
$course1 = ucwords($course1);
Upvotes: 0