Forum Moderators: coopster

Message Too Old, No Replies

Arrays and Strings

         

ramoneguru

1:43 am on Jun 5, 2005 (gmt 0)

10+ Year Member



Let's say I explode/store an array like so:

$someString = "Hello Webmaster World dot com";

$var = explode(" ", $someString);

//now I have the array:
// var[0] --> Hello
// var[1] --> Webmaster, etc...

How do I access the first character in each new array element? Since the strings are stored in an array I can't access them like normal variable strings.

example:
$temp = "hello";
echo "First character of temp is: $temp[0] <br/>";

But if they are stored in arrays how can I access the first char of the string (without storing it in a new variable)?

example:
$temp = var[0];
echo "First character of temp is: $temp[0] <br/>";

ekram

4:47 am on Jun 5, 2005 (gmt 0)

10+ Year Member



<?
$someString = "Hello Webmaster World dot com";

$var = explode(" ", $someString);

//now I have the array:
// var[0] --> Hello
// var[1] --> Webmaster, etc...
print_r($var); // just watch the array load perfectly

//echo substr($var[1], 0, 1); // for single line

for ($i=0; $i<sizeof($var); $i++) // for the array
{
echo "<br>".substr($var[$i], 0, 1)."<br>";
}

?>

dcrombie

10:55 am on Jun 5, 2005 (gmt 0)



$var[0][0]
should work - Strings are just Arrays of characters ;)

JamShady

2:48 pm on Jun 5, 2005 (gmt 0)

10+ Year Member



As of PHP 5, $var[0]{0} is the preferred behaviour. They're changing the access to a particular letter in the string to make it easier to recognise the differences between strings and arrays.

dcrombie

3:30 pm on Jun 5, 2005 (gmt 0)



Thanks JamShady, I didn't know that.

For this problem, you can also do something like:

$input = "Hello Webmaster World dot com"; 
preg_match_all("/\b([\w])[\w]+/", $input, $regs);
print_r($regs[1]);

;)

JamShady

3:25 am on Jun 6, 2005 (gmt 0)

10+ Year Member



No prob ;)

Or preg_match_all("/\b(\w)/", $input, $regs);

You don't need the square backets for single character definitions, its used for grouping (as opposed to normal brackets which are used to specify a particular pattern). Ala [\s\w]+ will match spaces or word characters, whereas (\s\w)+ only matches alternating spaces and word characters

ramoneguru

10:28 pm on Jun 9, 2005 (gmt 0)

10+ Year Member



Thanks all, that seriously helped me out of a jam.
--Nick