1

Ok I know this is simple, in fact damn simple, I did this in the last project about a week ago, but I don't know why it has skipped off my head.

Input:

$word = "stack";

What I want to do is:

$array = array("s", "t", "a", "c", "k");

Any help will be appreciated!

1
  • 1
    for information, you can do this : $foo = 'bar'; echo $foo[1]; //will print 'a'; Commented Sep 3, 2009 at 9:56

3 Answers 3

3

Your question isn't too clear, but I suspect you want to turn your string into an array. You don't have to, actually. You can just access $word as if it were an array:

$word = 'stack';
for ($i=0, $m = strlen($word); $i < $m; $i++)
    echo $word[$i], "\n";
Sign up to request clarification or add additional context in comments.

3 Comments

What if he wants to use foreach with that string? In PHP, strings are half-arrays, unfortunately.
Well, that'd be an odd way of going about things (I want to loop over this string, but it HAS to be foreach even though a for-loop would do). But, indeed, there are cases where you are better off using str_split(). But if at all possible I'd favor not using str_split() as it creates a new array and strlen($word) new strings.
I guess I figured it out why certain PHP aspects are so bad. Because people don't care about them.
2

str_split();

2 Comments

I feel so stupid..DAMN Thanks for fast reply, needed urgently!
Don't feel bad. It can be hard to find these PHP functions and there are a lot of them, more than most people know.
0

Try this:

var_dump(str_split("abc"));

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.