Using list() With explode() In PHP
Note: This post is over two years old and so the information contained here might be out of date. If you do spot something please leave a comment and we will endeavour to correct.
A simple way to convert a string into a set of variables is through the use of the explode() and list() functions. list() is a language construct (not really a function) that will convert an array into a list of variables. For example, to convert a simple array into a set of variables do the following:
In this example $variable1 now contains the value 1 and $variable2 contains the value 2. This can be adapted to use the explode() function to take a string and convert it into a set of variables. An example of this in use might be when dealing with addresses, simply explode the string using the comma and you have a set of variables.
You can now print out parts of the address like this:
The good thing about using this code is that even if part of the address isn’t present you will still get a variable for that space. Altering the previous example to remove the town and the city like this:
Has the effect of creating empty $town and $city variables. They should always be present as long as your address has the same number of parts.
Phil is the founder and administrator of #! code and is an IT professional working in the North West of the UK. Graduating in 2003 from Aberystwyth University with an MSc in Computer Science Phil has previously worked as a database administrator, on an IT help desk, systems trainer, web architect, usability consultant, blogger and SEO specialist. Phil has lots of experience building and maintaining PHP websites as well as working with associated technologies like JavaScript, HTML, CSS, XML, Flex, Apache, MySQL and Linux.
Want to know more? Need some help?
Let us help! Hire us to provide training, advice, troubleshooting and more.
Support Us!
Please support us and allow us to continue writing articles.
Extract / explode string into variables
Solution 1: Reference: http://us1.php.net/explode Explode should return an array of values. Gives you an array of the values: Question: I was expecting that the explode function of the following string would give me But the explode function gives me: and are both variables.
Extract / explode string into variables
i have an the following string from my database:
how can I extract / explode into variables
$data = ";5;78;27;56;66;71;"; $dataArr = explode(';',$data); for($i = 0; $i < count($dataArr); $i++)< $= $dataArr[$i]; >
Explode should return an array of values. Then you iterate through said values and dynamically assign a name to each one.
In my example code, you’ll get $var1, $var2, $var3 and so on.
array_filter( explode(‘;’, «;5;78;27;56;66;71;») );
The filter is to get rid of some empty values.
Gives you an array of the values:
Array ( [1] => 5 [2] => 78 [3] => 27 [4] => 56 [5] => 66 [6] => 71 )
Php — explode string into variables, In PHP 5.x, when assigning a value directly to another array, as an element of that array, list() values are assigned from right to left in PHP 5.x, not left to right. In other words, you’ll end up with array that is populated backwards (last value, first).
How to explode two variables with PHP
I was expecting that the explode function of the following string
$lines[1]="Start_time= ". $ST. ':' . $STIMI."\n" ;
would give me Array[0]= Start_time, Array[1]= $ST, Array[2]= :, Array [3]= $STIMI
But the explode function gives me: Array[0]= Start_time Array[1]= $ST:$STIMI
$ST and $STIMI are both variables. Any idea how to fix this
The explode function takes a parameter by which to explode the string. Presuming you are using a blank space you will need to add a blank space on either side of your colon.
$lines[1]="Start_time= ". $ST. ' : ' . $STIMI."\n" ;
Explode by using the «:» separator as opposed to » «
Mind that if you have «:» in your strings it will mess up your algorithm.
PHP explode() Function, Required. Specifies where to break the string: string: Required. The string to split: limit: Optional. Specifies the number of array elements to return. Possible values: Greater than 0 — Returns an array with a maximum of limit element(s) Less than 0 — Returns an array except for the last -limit elements() 0 — Returns an array with one …
Split string on multiple characters in PHP
I need to split an age into its components where the age is expressed as eg. 27y5m6w2d or any combination of those values. eg. 2w3d or 27d or 5y2d etc. Result has to be up to 4 variables $yrs, $mths, $wks and $days containing the appropriate numeric values.
I can do it with this code but am hoping there is something more efficient:
$pos = strpos($age, 'y'); if ($pos !== false) list($yrs, $age) = explode('y', $age); $pos = strpos($age, 'm'); if ($pos !== false) list($mths, $age) = explode('m', $age); $pos = strpos($age, 'w'); if ($pos !== false) list($wks, $age) = explode('w', $age); $pos = strpos($age, 'd'); if ($pos !== false) list($days, $age) = explode('d', $age);
If you have a suggestion, please run it in a 10,000 iteration loop and advise the results. The code above runs in an average of 0.06 seconds for 10,000 iterations. I use this code to test:
"; echo 'y='.$yrs.' m='.$mths.' w='.$wks.' d='.$days; ?>
I would suggest using regular expression matching with preg_match_all() like this:
$input = '2w3d' $matches = array(); preg_match_all('|(\d+)([ymwd])|', $input, $matches, PREG_SET_ORDER);
Where the output array $matches will hold all matches in this pattern:
$matches = array( // 0 => matched string, 1 => first capture group, 2 => second capture group 0 => array( 0 => '2w', 1 => '2', 2 => 'w' ), 1 => array( 0 => '3d', 1 => '3', 2 => 'd' ) );
EDIT :
Process this result like so:
$yrs = $mths = $wks = $days = 0; foreach($matches as $match) < switch($match[2]) < case 'y': $yrs = (int)$match[1]; break; case 'm': $mths = (int)$match[1]; break; case 'w': $wkss = (int)$match[1]; break; case 'd': $days = (int)$match[1]; break; >>
EDIT 2: Hacky alternative
Makes use of character comparison and takes around 0.4 seconds for 100.000 iterations.
$number = ''; for($j = 0, $length = strlen($input); $j < $length; $j++) < if($input[$j] < 'A') < $number .= $input[$j]; >else < switch($input[$j]) < case 'y': $yrs = (int)$number; break; case 'm': $mths = (int)$number; break; case 'w': $wks = (int)$number; break; case 'd': $days = (int)$number; break; >$number = ''; > >
I’d go with the following approach.
$age = '27y5m6w2d'; // Split the string into array of numbers and words $arr = preg_split('/(? <=[ymdw])/', $age, -1, PREG_SPLIT_NO_EMPTY); foreach ($arr as $str) < $item = substr($str, -1); // Get last character $value = intval($str); // Get the integer switch ($item) < case 'y': $year = $value; break; case 'm': $month = $value; break; case 'd': $day = $value; break; case 'w': $week = $value; break; >>
The code is more readable and slightly faster. I tested this with 10000 iterations and it took around just 0.0906 seconds.
You don’t need to bloat your code with a lookup array or a switch block.
Your input strings are predictably formatted (in order), so you can write a single regex pattern containing optional capture groups at each of the expected «units» in the input string. While using named capture groups provides some declarative benefit, it also bloats the regex pattern and the output array — so I generally don’t prefer to use them.
You will notice that there is a repeated format in the regex: (?:(\d+)unitLetter)? . This makes modifying/extending the pattern very simple. All of those subpatterns make the targeted substring «optional» and the final letter in the subpattern distinguishes what unit of time is being isolated.
In this case, the match output structure goes:
- [0] : the full string match (we don’t need it)
- [1] : yrs
- [2] : mths
- [3] : wks
- [4] : days
$strings = ['27y5m6w2d', '1m1w', '2w3d', '999y3w', '27d', '5y2d']; foreach ($strings as $string) < preg_match('~(?:(\d+)y)?(?:(\d+)m)?(?:(\d+)w)?(?:(\d+)d)?~', $string, $m); var_export([ 'yrs' =>$m[1] ?? '', 'mths' => $m[2] ?? '', 'wks' => $m[3] ?? '', 'days' => $m[4] ?? '', ]); echo "\n---\n"; >
array ( 'yrs' => '27', 'mths' => '5', 'wks' => '6', 'days' => '2', ) --- array ( 'yrs' => '', 'mths' => '1', 'wks' => '1', 'days' => '', ) --- array ( 'yrs' => '', 'mths' => '', 'wks' => '2', 'days' => '3', ) --- array ( 'yrs' => '999', 'mths' => '', 'wks' => '3', 'days' => '', ) --- array ( 'yrs' => '', 'mths' => '', 'wks' => '', 'days' => '27', ) --- array ( 'yrs' => '5', 'mths' => '', 'wks' => '', 'days' => '2', ) ---
Php — extract / explode string into variables, Browse other questions tagged php extract explode or ask your own question. The Overflow Blog Design patterns for asynchronous API communication
PHP: Can I safely use explode on a multi-byte string
Can I safely use explode() on a multi-byte string, specifically UTF8? Or do I need to use mb_split() ?
A multi-byte string is still just a string, and explode would happily split it on whatever delimiter you provide. My guess is that they will probably behave identically under most circumstances. If you are concerned about a particular situation, consider using this test script:
It’s worth pointing out that both explode() and mb_split() have the exact same parameter list — without any reference to language or character encoding. You should also realize that how your strings are defined in PHP depend on where and how you obtain your delimiter and the string to be exploded/split. Your strings might come from a text or csv file, a form submission in a browser, an API call via javascript, or you may define those strings right in your PHP script as I have here.
I might be wrong, but I believe that both functions will work by looking for instances of the delimiter in the string to be exploded and will split them.
How to explode two variables with PHP, @MaryE good, just so you understand, the explode function will take any string you pass as a second parameter, regardless of if it’s passed in as a variable, and split it using the string passed in to the first parameter as a split point. As you passed in a blank space as a split point, your string will be split at every blank space. Make …