Split a string into parts using explode

David Carr

3 min read - 5th May, 2011

A tutorial to split a string into parts using explode.

The code that will run to split the string into parts will be encased inside a function, start the function by using the word function followed by it's name in this case stringparts pass 2 parameters with it in parenthesis $parts and $times, $parts is the string to be split and $times is the number of times to split the string.

function stringparts($parts,$times){

Then use explode to split the string and add it to a variable, to explode the string using the word explode followed by 3 properties the fist tells it where to split the string in this case I've told it to split every word after a comma the second part is the string to split and the third is the number of times to split the string.

$chunks = explode(",", $parts, $times);

Then loop through all parts that have been split using a for loop, to use a for loop type for which tells php to expect to loop then define a variable to hold an integer with an initial value of zero ($i = 0) then tell it to count while the number of parts is less then the integer < count($chunks) then tell the loop to increment the integer ($i++) which will go up in value on each loop so first look $i will be 0 then on the second loop it will be 1 then 2 ..ect

for($i = 0; $i < count($chunks); $i++){

Then echo out the current value of the words since the words are stored in an array we can use the array to print the position out using $chunks[$i] the $i will be the actual number so if you were to type this out manually it would be $chunks[0], $chunks[0]..ect

echo "$i = $chunks[$i]
";


<p>then close the for loop and the function:</p>


```php
}
}

Then we define the string to be split by the function

$parts = 'one,two,three';


<p>At this point nothing would happen if you ran the script as you need to call the function for it to run to call the function simply type the function name and the parameters you want to run. The first part is the string to be split and the second is the number of times you want to split the string the number becomes $times inside the function.</p>


```php
stringparts($parts,3);

Here's the full script:

<?php
function stringparts($parts,$times){
  $chunks = explode(",", $parts, $times);
  for($i = 0; $i < count($chunks); $i++){
    echo "$i = $chunks[$i] <br />";
  }
}

$parts = 'one,two,three';
stringparts($parts,3);
?>

That's it you can now split a string into parts enjoy!

0 comments
Add a comment

Copyright © 2024 DC Blog - All rights reserved.