Page 1 of 1

Return string

Posted: Tue Sep 09, 2008 2:50 am
by treesa
Assume i have this string:
"hello";
if i give the number 2, the character 'l" has to be displayed.
i.e given the position, the charcter has to be displayed.how do i fetch the character of the string?



thanks

Re: Return string

Posted: Tue Sep 09, 2008 3:22 am
by Oren
Hmm... :?: not sure what you mean, but maybe this will help you:

Code: Select all

$str = 'hello';
$char = $str[1]; // $char == 'e'

Re: Return string

Posted: Tue Sep 09, 2008 3:35 am
by josh
also look at substr(). or while youre at it the rest of the string functions PHP has
http://us.php.net/manual/en/ref.strings.php

Re: Return string

Posted: Tue Sep 09, 2008 4:02 am
by treesa
assume im having a string......
str="This is a string."
Using random function,need to capitalize it.
eg: THis Is a STring
The input string can vary each time

Re: Return string

Posted: Tue Sep 09, 2008 4:47 am
by shaneiadt
Just get the length of the string using the count() function, loop through the characters in the string and maybe have a rand() function to random between 1 and 0 and if it's 1 Capitalize and if 0 leave it the way it is.

There you go :)

I hope that helped!

Re: Return string

Posted: Tue Sep 09, 2008 6:25 am
by jayshields
Are we doing your homework? The first question about characters in strings can be achieved using

Code: Select all

$str = 'Hello';
echo $str{2};

Re: Return string

Posted: Tue Sep 09, 2008 7:11 am
by Darkzaelus
treesa wrote:assume im having a string......
str="This is a string."
Using random function,need to capitalize it.
eg: THis Is a STring
The input string can vary each time

Code: Select all

 
<?php
$str='Hello';
$str2='';
for($i=0;$i<sizeof($str);$i++)
    $str2.=mt_rand(0,1)?strtoupper($str[$i]):strtolower($str[$i]);
return $str2;
//Will return a randomly capitalised word(s)
?>
 

Re: Return string

Posted: Tue Sep 09, 2008 10:48 pm
by treesa
thanks,
the above works only if we give strlen($str) instead of sizeof ($str).
also what does this line
$str2 .= mt_rand(0,1)?ucfirst($str[$i]):strtolower($str[$i]); indicate?
does it mean $str2 = $str2. mt_rand(0,1)?ucfirst($str[$i]):strtolower($str[$i]) ?

thanks

Re: Return string

Posted: Tue Sep 09, 2008 11:53 pm
by treesa
also please explain this mt_rand(0,1)?ucfirst($str[$i]):strtolower($str[$i]);
is this similar to if statement?

Re: Return string

Posted: Wed Sep 10, 2008 12:18 am
by josh
Yep,
The expression (expr1) ? (expr2) : (expr3) evaluates to expr2 if expr1 evaluates to TRUE, and expr3 if expr1 evaluates to FALSE.
http://us3.php.net/language.operators.comparison

Re: Return string

Posted: Wed Sep 10, 2008 10:30 am
by Darkzaelus
Basically it's shorthand for writing:

Code: Select all

 
$temp=mt_rand(0,1);
    if($temp==0)
        $str2.=strtoupper($str[$i]);
    else
        $str2.=strtolower($str[$i]);
 
Sorry bout that :P

Cheers, Darkzaelus