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

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

Related

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

Removing everything after the last instance of a specific character

Let's say I have a string, like this:
$my_string = 'hello_world-my_name_is-holl';
My goal is to run this through a function, and end up with:
'hello_world-my_name_is'
I want to get rid of everything after the last instance of a hyphen. There can be more than two. My idea was trying something like this:
$arr = explode("-", $my_string);
$arr = array_pop($arr);
$new_name = implode('', $arr);
But that doesn't seem to work. What's a good short way of achieving what I'm looking for?
The reason why your code doesn't work is twofold:
first off, array_pop() modifies the passed array PLUS returns what it popped off. That means what you are doing here is re-assigning "holl" (a string) to your $arr variable and therefore it is no longer an array. That is why the following implode function fails. The second argument needs to be an array, not a string.
Secondly, you'll want to use the hyphen as a glue when putting the array back together into a string. So, the following should work.
$my_string = 'hello_world-my_name_is-holl';
$arr = explode("-", $my_string);
$arr2 = array_pop($arr);
$new_name = implode('-', $arr);
echo $new_name;
As you can see, I assigned the popped-off "holl" to a new variable (in case you need it), but then imploded the original, but modified array $arr.

php array count includes trailing comma

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

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