I need to split my string input into an array at the commas.
Is there a way to explode a comma-separated string into a flat, indexed array?
Input:
9,admin#example.com,8
Output:
['9', 'admin#example', '8']
Try explode:
$myString = "9,admin#example.com,8";
$myArray = explode(',', $myString);
print_r($myArray);
Output :
Array
(
[0] => 9
[1] => admin#example.com
[2] => 8
)
$string = '9,admin#google.com,8';
$array = explode(',', $string);
For more complicated situations, you may need to use preg_split.
If that string comes from a csv file, I would use fgetcsv() (or str_getcsv() if you have PHP V5.3). That will allow you to parse quoted values correctly. If it is not a csv, explode() should be the best choice.
What if you want your parts to contain commas? Well, quote them. And then what about the quotes? Well, double them up. In other words:
part1,"part2,with a comma and a quote "" in it",part3
PHP provides the https://php.net/str_getcsv function to parse a string as if it were a line in a CSV file which can be used with the above line instead of explode:
print_r(str_getcsv('part1,"part2,with a comma and a quote "" in it",part3'));
Array
(
[0] => part1
[1] => part2,with a comma and a quote " in it
[2] => part3
)
explode has some very big problems in real life usage:
count(explode(',', null)); // 1 !!
explode(',', null); // [""] not an empty array, but an array with one empty string!
explode(',', ""); // [""]
explode(',', "1,"); // ["1",""] ending commas are also unsupported, kinda like IE8
this is why i prefer preg_split
preg_split('#,#', $string, NULL, PREG_SPLIT_NO_EMPTY)
the entire boilerplate:
/** #brief wrapper for explode
* #param string|int|array $val string will explode. '' return []. int return string in array (1 returns ['1']). array return itself. for other types - see $as_is
* #param bool $as_is false (default): bool/null return []. true: bool/null return itself.
* #param string $delimiter default ','
* #return array|mixed
*/
public static function explode($val, $as_is = false, $delimiter = ',')
{
// using preg_split (instead of explode) because it is the best way to handle ending comma and avoid empty string converted to ['']
return (is_string($val) || is_int($val)) ?
preg_split('#' . preg_quote($delimiter, '#') . '#', $val, NULL, PREG_SPLIT_NO_EMPTY)
:
($as_is ? $val : (is_array($val) ? $val : []));
}
Use explode() or preg_split() function to split the string in php with given delimiter
// Use preg_split() function
$string = "123,456,78,000";
$str_arr = preg_split ("/\,/", $string);
print_r($str_arr);
// use of explode
$string = "123,46,78,000";
$str_arr = explode (",", $string);
print_r($str_arr);
If anyone wants to convert comma seprated string into a list item using for-each then it will help you ...
This code is for blade template
#php
$data = $post->tags;
$sep_tag= explode(',', $data);
#endphp
#foreach ($sep_tag as $tag)
<li class="collection-item">{{ $tag}}</li>
#endforeach
//Re-usable function
function stringToArray($stringSeperatedCommas)
{
return collect(explode(',', $stringSeperatedCommas))->map(function ($string) {
return trim($string) != null ? trim($string) : null;
})->filter(function ($string) {
return trim($string) != null;
});
}
//Usage
$array = stringToArray('abcd, , dsdsd, dsds');
print($array);
//Result
{ "abcd", "dsdsd", "dsds" }
Related
Is there a split function in PHP that works similar to the JavaScript split()? For some reason explode() returns an array of length 1 when an empty string is given.
Example:
$aList = explode(",", ""); -> to return a 0-length array
$aList = explode(",", "1"); -> to return a 1-length array $aList[0] = 1
$aList = explode(",", "1,5"); -> to return a 2-length array $aList[0] = 1 and $aList[1] = 5
I have two suggestion for you
1. check empty string before explode
if( strlen($str) ){
$aList = explode(",", $str);
}
2. use empty method to check array
$aList = explode(",", $str);
if( empty($aList) ){}
if( !empty($aList) ){}
All you have to do is check the return value of "explode()":
https://www.php.net/manual/en/function.explode.php
If delimiter is an empty string (""), explode() will return FALSE.
PS:
Q: What's the rationale for "array of 1"?
A string that doesn't contain the delimiter will simply return a
one-length array of the original string (here, an "empty"string).
"GetSet" put it very well in his comment above:
Any split or explode will return 1. Logically, that's all there is
left.
Please Try this one.
implode(",", $aList);
This is split function in PHP.
str-split
spliti
I need to split my string input into an array at the commas.
Is there a way to explode a comma-separated string into a flat, indexed array?
Input:
9,admin#example.com,8
Output:
['9', 'admin#example', '8']
Try explode:
$myString = "9,admin#example.com,8";
$myArray = explode(',', $myString);
print_r($myArray);
Output :
Array
(
[0] => 9
[1] => admin#example.com
[2] => 8
)
$string = '9,admin#google.com,8';
$array = explode(',', $string);
For more complicated situations, you may need to use preg_split.
If that string comes from a csv file, I would use fgetcsv() (or str_getcsv() if you have PHP V5.3). That will allow you to parse quoted values correctly. If it is not a csv, explode() should be the best choice.
What if you want your parts to contain commas? Well, quote them. And then what about the quotes? Well, double them up. In other words:
part1,"part2,with a comma and a quote "" in it",part3
PHP provides the https://php.net/str_getcsv function to parse a string as if it were a line in a CSV file which can be used with the above line instead of explode:
print_r(str_getcsv('part1,"part2,with a comma and a quote "" in it",part3'));
Array
(
[0] => part1
[1] => part2,with a comma and a quote " in it
[2] => part3
)
explode has some very big problems in real life usage:
count(explode(',', null)); // 1 !!
explode(',', null); // [""] not an empty array, but an array with one empty string!
explode(',', ""); // [""]
explode(',', "1,"); // ["1",""] ending commas are also unsupported, kinda like IE8
this is why i prefer preg_split
preg_split('#,#', $string, NULL, PREG_SPLIT_NO_EMPTY)
the entire boilerplate:
/** #brief wrapper for explode
* #param string|int|array $val string will explode. '' return []. int return string in array (1 returns ['1']). array return itself. for other types - see $as_is
* #param bool $as_is false (default): bool/null return []. true: bool/null return itself.
* #param string $delimiter default ','
* #return array|mixed
*/
public static function explode($val, $as_is = false, $delimiter = ',')
{
// using preg_split (instead of explode) because it is the best way to handle ending comma and avoid empty string converted to ['']
return (is_string($val) || is_int($val)) ?
preg_split('#' . preg_quote($delimiter, '#') . '#', $val, NULL, PREG_SPLIT_NO_EMPTY)
:
($as_is ? $val : (is_array($val) ? $val : []));
}
Use explode() or preg_split() function to split the string in php with given delimiter
// Use preg_split() function
$string = "123,456,78,000";
$str_arr = preg_split ("/\,/", $string);
print_r($str_arr);
// use of explode
$string = "123,46,78,000";
$str_arr = explode (",", $string);
print_r($str_arr);
If anyone wants to convert comma seprated string into a list item using for-each then it will help you ...
This code is for blade template
#php
$data = $post->tags;
$sep_tag= explode(',', $data);
#endphp
#foreach ($sep_tag as $tag)
<li class="collection-item">{{ $tag}}</li>
#endforeach
//Re-usable function
function stringToArray($stringSeperatedCommas)
{
return collect(explode(',', $stringSeperatedCommas))->map(function ($string) {
return trim($string) != null ? trim($string) : null;
})->filter(function ($string) {
return trim($string) != null;
});
}
//Usage
$array = stringToArray('abcd, , dsdsd, dsds');
print($array);
//Result
{ "abcd", "dsdsd", "dsds" }
I have a string of this type:
string(11) "2=OK, 3=OK"
from a text file. But I would like to convert it into an array of keys this type :
array (
[2] => Ok
[3] => Ok
)
I was wondering how we could do that in PHP.
Note:- I normally use explode() and str_split() for the conversions string into array but in this case I don't know how to do it.
use explode(), foreach() along with trim()
<?php
$string = "2=OK, 3=OK" ;
$array = explode(',',$string);
$finalArray = array();
foreach($array as $arr){
$explodedString = explode('=',trim($arr));
$finalArray[$explodedString[0]] = $explodedString[1];
}
print_r($finalArray);
https://3v4l.org/ZsNY8
Explode the string by ',' symbol. You will get an array like ['2=OK', ' 3=OK']
Using foreach trim and explode each element by '=' symbol
You can use default file reading code and traverse it to achieve what you want,
$temp = [];
if ($fh = fopen('demo.txt', 'r')) {
while (!feof($fh)) {
$temp[] = fgets($fh);
}
fclose($fh);
}
array_walk($temp, function($item) use(&$r){ // & to change in address
$r = array_map('trim',explode(',', $item)); // `,` explode
array_walk($r, function(&$item1){
$item1 = explode("=",$item1); // `=` explode
});
});
$r = array_column($r,1,0);
print_r($r);
array_walk — Apply a user supplied function to every member of an array
array_map — Applies the callback to the elements of the given arrays
explode — Split a string by a string
Demo.
You can use preg_match_all along with array_combine, str_word_count
$string = "2=OK, 3=OK" ;
preg_match_all('!\d+!', $string, $matches);
$res = array_combine($matches[0], str_word_count($string, 1));
Output
echo '<pre>';
print_r($res);
Array
(
[2] => OK
[3] => OK
)
LIVE DEMO
I have some date values (each with a trailing = sign) stored as a &-delimited string.
My $_POST['dates'] string looks like this:
23.08.18=&22.08.18=&21.08.18=
I'm trying the following PHP code to extract the dates before inserting them into my database table. The code is currently not working.
foreach(explode('&', $_POST['dates']) as $value)
{
$value1 = explode('=', $value);
foreach ($value1 as $x) {
}
}
How can I isolate the date values?
The function that you might be looking for is parse_str(). You have a valid query string (well, kind of) with keys but no values, so you merely need to parse it and isolate the keys(dates). Unfortunately, the parser converts your dots to underscores.
Code: (Demo)
$string = '23.08.18=&22.08.18=&21.08.18=';
parse_str($string, $out);
var_export(array_keys($out));
Output:
array (
0 => '23_08_18',
1 => '22_08_18',
2 => '21_08_18',
)
And of course, you can repair the modified date values with str_replace(). See this demo.
Or if you want to disregard parse_str(), you can use just one regex call that divides the string on = followed by an optional &:
Code: (Demo)
$string = '23.08.18=&22.08.18=&21.08.18=';
var_export(preg_split('~=&?~', $string, -1, PREG_SPLIT_NO_EMPTY));
Output:
array (
0 => '23.08.18',
1 => '22.08.18',
2 => '21.08.18',
)
Or without regex, just trim the last = and explode on =&: (Demo)
$string = '23.08.18=&22.08.18=&21.08.18=';
var_export(explode('=&', rtrim($string, '=')));
// same output as preg_split()
<?php
$data = '23.08.18=&22.08.18=&21.08.18=';
//$delimiters has to be array
//$string has to be array
function multiexplode ($delimiters,$string) {
$ary = explode($delimiters[0],$string);
array_shift($delimiters);
if($delimiters != NULL) {
foreach($ary as $key => $val) {
$ary[$key] = multiexplode($delimiters, $val);
}
}
return $ary;
}
$exploded = multiexplode(array("=","&"),$data);
var_dump($exploded);
The result should be:
array (size=3)
0 => string '23.08.18' (length=8)
2 => string '22.08.18' (length=8)
4 => string '21.08.18' (length=8)
We need to use array_filter.
http://php.net/manual/en/function.explode.php
[EDIT] mickmackusa's answer is the right tool for parse url parameters into variables.
I have the below line which takes a string, explodes it to an array by ',' and then trims any whitespace for each array item.
$essentialArray = array_map('trim', explode(',', $essential_skills));
However when $essential_skills string = "" $essentialArray will equal Array ( [0] => )
But I need it to equal Array() so that I can call empty() on on it.
That is normal and logical behavior of the function.
Look at it this way: what does the explode() call return? An array with a single element which is the empty string. The array_map() call does not change that at all.
So you might ask: why does explode('') result in an array with a single element which is the empty string? Well, why not? It takes the empty string and splits it at all comma characters in there, so exactly no times. That means the empty string stays unaltered. But it does not magically vanish!
explode return Array ( [0] => ), so you need to check your string before array_map
here is a one solution
$exploderesult = $essential_skills ? explode(',', $essential_skills) : array();
$essentialArray = array_map('trim', $exploderesult );
The easiest solution here will be just filter result array, like this:
$essentialArray = array_filter(array_map('trim', explode(',', $essential_skills)));
but proper way is:
if ($essential_skills === '') {
$essentialArray = [];
}
else {
$essentialArray = array_map('trim', explode(',', $essential_skills));
}