I've got a list of data with in the following format:
data\n
data\n
data\n
data\n
data\n
Now I try to explode it into an array with
$array = explode("\n", $dataList);
What happens next is that there is a key with no data, I think it is because of the \n on the end.
Is there a way to explode it so that the last key isn't set?
Thanks!
Not directly. You can either:
Remove the trailing "\n" with trim.
Remove the last element of $array with array_pop.
Use preg_split instead with the flag PREG_SPLIT_NO_EMPTY.
Remove empty values by:
$array = array_filter( $array );
After you explode, use array_pop() to pop the last item:
$array = explode("\n", $dataList);
array_pop($array);
You can add an if statement using count() and empty() if you want to check if the last item contains something other than a linebreak character, but that should get you what you need.
Related
Is it possible with php to make a string of, say, <a>-elements comma-separated?
The situation is that a foreach loop appends a number of <a> links to an $output variable one after the other:
$output = '<a>link</a><a>link</a><a>link</a><a>link</a><a>link</a>';
Is it afterwards possible in php to comma-separate them and achieve the below string?
$output = '<a>link</a>,<a>link</a>,<a>link</a>,<a>link</a>,<a>link</a>';
Or is the most efficient way to add the comma inside the foreach loop (and then to use an if-command to skip the last one, or something like that, since that will add one comma too many)?
$output = preg_replace("/a><a","/a>,<a",$output);
I'd argue that the array implode method is probably most common way to concatenate multiple elements like this, which has already been posted in another answer.
Depending on your situation, this might however not always be the case, so for the sake of completion I'd like to add that you can also use the rtrim function to easily remove any trailing commas when concatenating strings:
foreach($links as $link) {
$output .= '<a>link</a>,';
}
$output = rtrim($output, ',');
Documentation for rtrim can be read here
A simple replace might do the job for you:
preg_replace('/a><a/','a>,<a',$s);
In your foreach loop, rather than concatenating the item on to the end of an existing string, push them to an array:
$parts = array();
foreach($list as $item){
$parts[] = "<a>$item</a>";
}
Then, you can simply join (implode) the array elements together to get your desired result:
$output = implode(',', $parts);
there are 2 solutions
solution 1 (with str_replace()):
$output = '<a>link</a><a>link</a><a>link</a><a>link</a><a>link</a>';
echo str_replace("</a>","</a>,", $output);
Solution 2 (with explode and implode method):
$exploded = explode("</a>",$output);
echo implode("</a>,", $exploded);
Side Note: you can remove the last `"," by using rtrim() method
You can replace </a> with </a>,, then trim the last `,', check Demo
echo rtrim(str_replace("</a>","</a>,",$output),",");
Due to bad DB design, there may be several values in a column # each row in a table. So I had to take in every string, check if commas exist (multiple values) & place each element into the end of an array.
Did try out functions like strpos, explode, array_push etc. With the folllowing code, how do i input ONLY the multiple elements into the end of an array, without creating another & placing that into an existing array?
$test = array();
$test = array ("testing");
$str = 'a,b,c,d';
$parts = explode(',', $str);
array_push ($test, $parts); //another array inserted into $test, which is not what I want
print_r($test);
Use array_merge.
$test = array_merge($test, $parts);
Example: http://3v4l.org/r7vaB
I have an array which I get from an exploded url (using $_GET).
The elements in the url are separated by commas but when I COUNT the elements the result includes the final comma. Eg: '?list=jonny,sally,bob,' returns '4' when '?list=jonny,sally,bob' returns '3'. I can't avoid the final comma as they are genrated with them automatically but I need to return 3 on both examples. Any ideas please?? Thanks
$list = explode(",", $_GET['list']);
$listCount = count($list);
//$listCount =(int)$listCount -1;
//$list[$listCount]=str_replace($list[$listCount],',','');
echo $listCount;
NB: the commented out lines are a failed attempt to remove the comma. But $list[$listCount] ,ie the final array element doesn't seem to exist even though it is counted
If you want to trim any extra commas at the start or end of the string, use trim(). If you want it at the end of the string, you can use rtrim().
$list = explode(",", $_GET['list']);
to
$list = explode(",", trim($_GET['list'], ','));
Trim any commas first:
$strList = rtrim($_GET['list'], ",")
$arrList = explode(",", $strList);
Array_filter will remove any empty values from your array, so in case you have two commas in a row, it will remove empty values caused by that also.
$list = array_filter(explode(",", $_GET['lists']));
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
How can I add a variable to an array? Let say I have variable named $new_values:
$new_values=",543,432,888"
And now I would like to add $new_values to function. I tried in that way:
phpfunction1(array(114,763 .$new_values. ), $test);
but I got an error Parse error: syntax error, unexpected T_VARIABLE, expecting ')'
How my code should look if I would like to have array(114,763,543,432,888)?
$new_values=",543,432,888";
should be converted to an array:
$new_values= explode(',', "543,432,888");
and merged to existing values with:
array_merge(array(114,763), $new_values);
Whole code should looks like:
$new_values = explode(',', "543,432,888");
$values = array(114,763);
$values = array_merge($values, $new_values);
phpfunction1($values, $test);
If you pass to explode a string that is starting with , you will get first empty element, so avoid it.
if you have an array already i.e.
$values = array(543,432,888);
You can add to them by : $values[]=114; $values[]=763;
Apologies if I missed the point there...
In your example, $new_values is a string, but, since it's comma delimited, you can create an array directly from it. Use $new_array = explode(',', $new_values); to create an array from the string.
You need to convert the string into an array using the explode function and then use the array_merge function to merge the two arrays into one:
$new_values=",543,432,888";
$currentArray=array(114,763);
$newArray=array_merge($currentArray,explode(',',$new_values));
functionX($newArray...)
But watch out for the empty array element because of the first comma.
For that use "trim($new_values, ',')" - see answer from rajesh.
you can do like this.
$old_values = array(122,555);
$new_values=",543,432,888";
$values = explode(',', trim($new_values, ','));
$result = array_merge($old_values, $values);
print_r($result);
try array merge
looks like this
phpfunction1(array_merge(array(114,763) ,$new_values), $test);
and yes your first array is not an array
change it to this
$new_values=Array(543,432,888);