Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations biv343 on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Problem with custom functions

Status
Not open for further replies.

748323

Programmer
Dec 10, 2004
70
US
I tried creating my own function that will reverse a string. I know I can use strrev(); but that's not fun, and it doesn't teach me anything :)

<?

function reverse_string($string, $var2) {
$str_len = strlen($string);
for($i = $str_len; $i >= 0; $i--) {
$var2 .= $string{$i};
}
}

reverse_string("1234567890", $new_string);
echo $newstring;

?>

When I try to echo $newstring, nothing comes up. What am I doing wrong?
 
Is $new_string supposed to be the same as $newstring? Have you tried return?
Code:
function reverse_string($string)
{
  $str_len = strlen($string);
  for($i = $str_len; $i >= 0; $i--)
  {
    $var2 .= $string{$i};
  }
  return $var2
}

echo reverse_string("1234567890");
 
I don't want the function to reverse the string. I want it to reverse it, and then place it in the variable indicated in the second parameter of the custom function.

I will try the $new_string thing. What a stupid mistake of me to take :(
 
Code:
<?

function reverse_string($string, $var2) {
$str_len = strlen($string);
for($i = $str_len; $i >= 0; $i--) {
$var2 .= $string{$i};
}
}

reverse_string("1234567890", $newstring);
echo $newstring;

?>

Still didn't work
 
How about
Code:
$newstring = reverse_string("1234567890");
on my code. The way you're doing it cannot work, because variables in the function are not available outside that function.
 
Code:
<?

function reverse_string($string) {
$str_len = strlen($string);
for($i = $str_len; $i >= 0; $i--) {
$var2 .= $string{$i};
}
return $var2;
}

$newstring = reverse_string("123456789");
echo $newstring;

?>

Okay. Thanks. That's all I could come up with. I didn't know that variables in a function are only used for that function!

 
Try googling for "php parameter function reference" or look up what the & operator does to a function parameter. The key phrase you're looking for is "pass by reference".
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top