php array count includes trailing comma - php

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']));

Related

how to input elements instead of another array, into end of array?

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

Remove characters from string based on user input

Suppose I have a string:
$str="1,3,6,4,0,5";
Now user inputs 3.
I want that to remove 3 from the above string such that above string should become:
$str_mod="1,6,4,0,5";
Is there any function to do the above?
You can split it up, remove the one you want then whack it back together:
$str = "1,3,6,4,0,5";
$userInput = 3;
$bits = explode(',', $str);
$result = array_diff($bits, array($userInput));
echo implode(',', $result); // 1,6,4,0,5
Bonus: Make $userInput an array at the definition to take multiple values out.
preg_replace('/\d[\D*]/','','1,2,3,4,5,6');
in place of \d just place your digit php
If you don't want to do string manipulations, you can split the string into multiple pieces, remove the ones you don't need, and join the components back:
$numberToDelete = 3;
$arr = explode(',',$string);
while(($idx = array_search($numberToDelete, $components)) !== false) {
unset($components[$idx]);
}
$string = implode(',', $components);
The above code will remove all occurrences of 3, if you want only the first one yo be removed you can replace the while by an if.

PHP or javascript: Flip order of text rows (not MySQL)

How can I flip the order of text
$string = 'last row
something inbetween
first row';
Result should be:
first row
something inbetween
last row
Note this is no A-Z ordering, just flipping it.
Is it possible? A solution in PHP, javascript or jquery would be welcome
You could explode the string into an array, reverse it and put it back together:
$a=explode("\n",$string);
$string=implode("\n",array_reverse($a));
You can split the string and reverse the array:
$array = explode("\n", $string);
$array = array_reverse($array);
$string = implode("\n", $array);
Edit: no one wrote an javascript solution (same logic as php script):
var string = string.split("\n").reverse().join("\n");
Edit: an example: http://jsfiddle.net/ceKyF/
You only got PHP answers, here is a javascript one:
// Split the string into an array
var arr = string.split( '\n' )
// Reverse the array
arr.reverse()
// Join the array back into a string
string = arr.join( '\n' )
This can be done in one line:
string = string.split( '\n' ).reverse().join( '\n' )

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

Explode datalist into array

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.

Categories