PHP Questions Home | Register | Login
Categories
Arrays
Files
Forms
Creating PDFs
PHP Errors
Functions
Images
MySQL
Numbers
Others
Strings
Website
Unanswered

PHP Forums
Forums Index
MySQL Forum
PHP Forum
Flash/Actionscript
Javascript
Web design

More PHP
PHP Functions
Top Questions
Ask a Question
PHP Interview Questions
PHP Jobs
Ecommerce
IT Questions
Business Websites

Sponsors

sponsor ad
My Salary
PHP Developer Salary
Advertise Here

PHP Questions Forums : PHP Questions and Answers

Jump to Last Post

Turning a string of text into an array

By: Timjohns [28-January-10 5:26AM]
25 posts
picture

Here's a function in PHP that was added reasonably recently that those who learned PHP years ago might not know that is a quick and convenient way of putting each member of a string into an array.

In the old days, if you had, let's say, a string of numbers: 32123214 and you wanted to turn that into an array, you had to put a while loop over each substring of the numbers and place into an array.

Now you can just use the str_split function to do it for you (with PHP 5 onwards), like this:

$numbers = "123235243";
$numberarray = str_split($numbers);
print_r($numbers); //echoes out the array with one number per element

Re : Turning a string of text into an array


Timjohns [29-January-10 6:15AM]
25 posts
picture

Just for completeness I thought I would pass the method for turning a string like the above into an array if you don't have access to PHP5 and therefore need another way of turning a string into an array in PHP.

You can do it like this:

$numbers = "12345632";
$len = strlen($numbers);
$count = 0;
$numberarray = array();
while($count < $len) {
$numberarray[] = substr($numbers,$count,1);
$count++;
}

and that's it: $numberarray now contains the same as using the str_split function in the original post: so you can see how much quicker it is with str_split!

Re : Turning a string of text into an array


Sallyjones [3-March-10 4:26PM]
12 posts
picture

If you want to turn a string into an array then you can also use a delimiter to do this with the explode function.

So you might have something full of commas then split on the commas using explode.

If you want to do it on a regular expression then you can use split to do that instead - say if you have a string like a3d4f5g4g6df7 or whatever then you can split on the numbers, say, to get an array of just the letters there with just one line of code which is pretty neat really!

Previous: Custom Sorting Arrays In PHP
Next: Multiple Checkbox



Custom Search