array_map does not give an empty array - php

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));
}

Related

Inverse of array implode() in php [duplicate]

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" }

explode on empty string returns an array of length 1

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

Using a dynamic values in as array using php [duplicate]

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" }

Trim string with array using PHP

How can i trim with array of string in php. If I have an dynamic array as follows :
$arr = array(' ','<?php','?>',"'",'"');
so how can i use this array in trim() to remove those string, I tried very hard in the code below :
$text = trim(trim(trim(trim(trim($text),'<?php'),'?>'),'"'),"'");
but i can not use this because array is dynamic, it may have more than 1000 values.
It takes a lot of time to turn into a loop even after trying it.So I can do anything as follows
$text = trim($text, array(' ','<?php','?>',"'",'"') );
It's possible to apply trim() function to an array. The question seems to be unclear but you can use array_map(). Unclear because there are other enough possible solutions to replace substrings. To just apply trim() function to an array, use the following code.
$array = array(); //Your array
$trimmed_array = array_map('trim', $array); //Your trimmed array is here
If you also want to fulfill the argument requirement in trim() you can apply a custom anonymous function to array_map() like this:
$array = array(); //Your array
$trimmed_array = array_map(function($item){
return trim($item, 'characters to be stripped');
}, $array); //Your trimmed array is here

using explode function to read a string

My code reads a line from a file, splits the line into elements, and is supposed to put the elements in an array.
I used explode, but it does not put the elements into the array in sequential order.
Example: for input
line: 1000 3000 5000
This is what happens
$a=fgets($file); // $a= 1000 3000 5000
$arr= explode(" ",$a);
$u=$arr[3]; // $u=1000
$w=$arr[6]; // $w=3000
$x=$arr[10]; // $x=5000
This is the desired order:
$u=$arr[0]; // $u=1000
$w=$arr[1]; // $w=3000
$x=$arr[2]; // $x=5000
Why doesn't explode put data sequentially into the array?
It always puts them in sequentially. IF you are seeing this behavior then you must have extra in the document that are being exploded upon resluting in empty array elements. You will either need to pre-process the string or prune empty elements from the array.
Alternatively you could use preg_split with the PREG_SPLIT_NO_EMPTY setting.
Dome examples of that you are trying to do:
// using regex
$arr = preg_split("/ /", $a, PREG_SPLIT_NO_EMPTY);
// pruning the array
$arr = explode(" ", $a);
$arr = array_keys($a, '');
In your example, it's going to put a new array entry per every space.
To get what you're looking for, the returned string would have to be "$u=1000_$w=3000_$x=5000" (underscores represent spaces here)
An alternate way to do this would be to use array_filter to remove the empty elements i.e.
$arr = explode( ' ', $a ); // split string into array
$arr = array_filter( $arr ); // remove empty elements from array
$arr = array_values( $arr ); // strip old array keys giving sequential numbering, i.e. 0,1,2

Categories