This question already has answers here:
Convert a comma-delimited string into array of integers?
(17 answers)
Closed 9 years ago.
Say I have a string like so $thestring = "1,2,3,8,2".
If I explode(',', $thestring) it, I get an array of strings. How do I explode it to an array of integers instead?
array_map also could be used:
$s = "1,2,3,8,2";
$ints = array_map('intval', explode(',', $s ));
var_dump( $ints );
Output:
array(5) {
[0]=> int(1)
[1]=> int(2)
[2]=> int(3)
[3]=> int(8)
[4]=> int(2)
}
Example codepad.
Use something like this:
$data = explode( ',', $thestring );
array_walk( $data, 'intval' );
http://php.net/manual/en/function.array-walk.php
For the most part you shouldn't really need to (PHP is generally good with handling casting strings and floats/ints), but if it is absolutely necessary, you can array_walk with intval or floatval:
$arr = explode(',','1,2,3');
// use floatval if you think you are going to have decimals
array_walk($arr,'intval');
print_r($arr);
Array
(
[0] => 1
[1] => 2
[2] => 3
)
If you need something a bit more verbose, you can also look into settype:
$arr = explode(",","1,2,3");
function fn(&$a){settype($a,"int");}
array_walk($f,"fn");
print_r($f);
Array
(
[0] => 1
[1] => 2
[2] => 3
)
That could be particularly useful if you're trying to cast dynamically:
class Converter {
public $type = 'int';
public function cast(&$val){ settype($val, $this->type); }
}
$c = new Converter();
$arr = explode(",","1,2,3,0");
array_walk($arr,array($c, 'cast'));
print_r($arr);
Array
(
[0] => 1
[1] => 2
[2] => 3
[3] => 0
)
// now using a bool
$c->type = 'bool';
$arr = explode(",","1,2,3,0");
array_walk($arr,array($c, 'cast'));
var_dump($arr); // using var_dump because the output is clearer.
array(4) {
[0]=>
bool(true)
[1]=>
bool(true)
[2]=>
bool(true)
[3]=>
bool(false)
}
Since $thestring is an string then you will get an array of strings.
Just add (int) in front of the exploded values.
Or use the array_walk function:
$arr = explode(',', $thestring);
array_walk($arr, 'intval');
$thestring = "1,2,3,8,a,b,2";
$newArray = array();
$theArray = explode(",", $thestring);
print_r($theArray);
foreach ($theArray as $theData) {
if (is_numeric($theData)) {
$newArray[] = $theData;
}
}
print_r($newArray);
// Output
Original array
Array ( [0] => 1 [1] => 2 [2] => 3 [3] => 8 [4] => a [5] => b [6] => 2 )
Numeric only array
Array ( [0] => 1 [1] => 2 [2] => 3 [3] => 8 [4] => 2 )
$arr=explode(',', $thestring);
$newstr = '';
foreach($arr as $key=>$val){
$newstr .= $val;
}
Related
I'm get data string lat and long google maps polygon. I want to convert this value to array .
$value = "(-6.2811957386588855, 106.70141951079609),(-6.281142416506361, 106.70432702536823),(-6.2781776962328815, 106.70438066954853),(-6.2781776962328815, 106.70136586661579)";
I want the result like this Array :
$polygon = array(
array(-6.2811957386588855, 106.70141951079609),
array(-6.281142416506361, 106.70432702536823),
array(-6.2781776962328815, 106.70438066954853),
array(-6.2781776962328815, 106.70136586661579),
);
You can convert the string to valid JSON by converting parentheses to square brackets and adding a [] layer around the outside, and then json_decode it:
$value = '(-6.2811957386588855, 106.70141951079609),(-6.281142416506361, 106.70432702536823),(-6.2781776962328815, 106.70438066954853),(-6.2781776962328815, 106.70136586661579)';
$polygon = json_decode('[' . str_replace(array('(', ')'), array('[', ']'), $value) . ']', true);
print_r($polygon);
Output:
Array
(
[0] => Array
(
[0] => -6.2811957386589
[1] => 106.7014195108
)
[1] => Array
(
[0] => -6.2811424165064
[1] => 106.70432702537
)
[2] => Array
(
[0] => -6.2781776962329
[1] => 106.70438066955
)
[3] => Array
(
[0] => -6.2781776962329
[1] => 106.70136586662
)
)
Demo on 3v4l.org
Using preg_match_all() and array_walk() you can parse the coordinates as an array
$value = '(-6.2811957386588855, 106.70141951079609),(-6.281142416506361, 106.70432702536823),(-6.2781776962328815, 106.70438066954853),(-6.2781776962328815, 106.70136586661579)';
preg_match_all('/\(([0-9\-\s,.]+)\)/', $value, $matches);
array_walk($matches[1], function(&$val) { $val = explode(',', $val); });
$coordinates = $matches[1];
print_r($coordinates);
Using preg_match_all() get all the coordinates as array of string
Using array_walk() make an iteration over the coordinated array and explode by the delimiter of comma (,)
Working demo.
Regex demo.
You can use explode() function like this
$string = '(-6.2811957386588855, 106.70141951079609),(-6.281142416506361, 106.70432702536823),(-6.2781776962328815, 106.70438066954853),(-6.2781776962328815, 106.70136586661579)';
foreach(explode('),(',trim($string,'()')) as $single_array)
{
$sub_array= array();
foreach(explode(',',$single_array) as $sbs_array)
{
$sub_array[] = $sbs_array;
}
$result[] = $sub_array;
}
print_r ($result);
Output :
Array
(
[0] => Array
(
[0] => -6.2811957386588855
[1] => 106.70141951079609
)
[1] => Array
(
[0] => -6.281142416506361
[1] => 106.70432702536823
)
[2] => Array
(
[0] => -6.2781776962328815
[1] => 106.70438066954853
)
[3] => Array
(
[0] => -6.2781776962328815
[1] => 106.70136586661579
)
)
Demo : https://3v4l.org/6HEAG
You can use explode with trim and array_map
$r = explode('),(',trim($value,'()'));
$c = array_map(function($v){return explode(',',$v);}, $r);
print_r($c);
Working example : https://3v4l.org/fFAS0
I suggest using preg_match_all with array_map
$value = '(-6.2811957386588855, 106.70141951079609),(-6.281142416506361, 106.70432702536823),(-6.2781776962328815, 106.70438066954853),(-6.2781776962328815, 106.70136586661579)';
preg_match_all('#\(([\-\d\.]+),\s+([\-\d\.]+)\)#', $value, $matches);
$geo = array_map(function ($a, $b) {
return [(float)$a, (float)$b];
}, $matches[1], $matches[2]);
Output:
array(4) {
[0]=>
array(2) {
[0]=> float(-6.2811957386589)
[1]=> float(106.7014195108)
}
[1]=>
array(2) {
[0]=> float(-6.2811424165064)
[1]=> float(106.70432702537)
}
[2]=>
array(2) {
[0]=> float(-6.2781776962329)
[1]=> float(106.70438066955)
}
[3]=>
array(2) {
[0]=> float(-6.2781776962329)
[1]=> float(106.70136586662)
}
}
Regex
I have an array like this
$array = array( [0] => 'red1', [1] => 'blue1', [2] => 'red2', [3] => 'red3', [4] => 'blue2' );
A want to reverse order of elements with red value only so it looks like this:
$array = array( [0] => 'red3', [1] => 'blue1', [2] => 'red2', [3] => 'red1', [4] => 'blue2' );
I think a possible solution might be to:
Get all the values from the $array that you are looking for and
store them in an array $found
Reverse the values in $found keeping the keys
Replace the values in $array with the values from $found using
the key
For example:
$array = array(0 => 'red1', 1 => 'blue1', 2 => 'red2', 3 => 'red3', 4 => 'blue2');
// First get all the values with 'red' and store them in an array
$found = preg_grep('/red\d+/', $array);
// Reverse the values, keeping the keys
$found = array_combine(
array_keys($found),
array_reverse(
array_values($found)
)
);
// Then replace the values of $array with values having the same keys in $found
$array = array_replace($array, $found);
var_dump($array);
Will result in:
array(5) {
[0]=>
string(4) "red3"
[1]=>
string(5) "blue1"
[2]=>
string(4) "red2"
[3]=>
string(4) "red1"
[4]=>
string(5) "blue2"
}
You can catch red's quote to a new array and sort them.
<?php
$arr = array(
'red1',
'blue1',
'red2',
'red3',
'blue2'
);
$sortArr = array();
for ($i=0; $i < sizeof($arr); $i++) {
if(strstr($arr[$i], "red")){
$sortArr[] = &$arr[$i];
}
}
?>
I think you can do using searching specific words by strpos and sorting array by ksort (sort associative arrays in ascending order, according to the key)
foreach ($array as $key => $value) {
if(strpos($value,"red") !== false){
($key === 0) ? $index = 3 : (($key === 3) ? $index = 0 : $index = 2);
$temp[$index] = $value;
}
else {
$temp[$key] = $value;
}
}
ksort($temp);
var_dump($temp);
[But It will not work in larger array than this]
This question already has answers here:
How to Flatten a Multidimensional Array?
(31 answers)
Closed 2 years ago.
I'm looking to find a way to merge all child arrays into one large array.
array (
[0] =
[0] = '0ARRAY',
[1] = '1ARRAY'
[1] =
[0] = '2ARRAY',
[1] = '3ARRAY'
)
into
array (
[0] = '0ARRAY', [1] = '1ARRAY', [2] = '2ARRAY', [3] = '3ARRAY'
)
Without using array_merge($array[0],$array[1]) because I don't know how many arrays there actually are. So I wouldn't be able to specify them.
Thanks
If I understood your question:
php 5.6+
$array = array(
array('first', 'second'),
array('next', 'more')
);
$newArray = array_merge(...$array);
Outputs:
array(4) { [0]=> string(5) "first" [1]=> string(6) "second" [2]=> string(4) "next" [3]=> string(4) "more" }
Example: http://3v4l.org/KA5J1#v560
php < 5.6
$newArray = call_user_func_array('array_merge', $array);
If it's only two levels of array, you can use
$result = call_user_func_array('array_merge', $array);
which should work as long as $array isn't completely empty
$new_array = array();
foreach($main_array as $ma){
if(!empty($ma)){
foreach($ma as $a){
array_push($new_array, $a);
}
}
}
You can try it by placing these values:
$main_array[0][0] = '1';
$main_array[0][1] = '2';
$main_array[1][0] = '3';
$main_array[1][1] = '4';
OUTPUT:
Array ( [0] => 1 [1] => 2 [2] => 3 [3] => 4 )
I have two arrays in php as shown in the code
<?php
$a=array('0'=>array('500'=>'1','502'=>'2'));
$b=array('0'=>array('503'=>'3','504'=>'5'));
print_r(array_merge($a[0],$b[0]));
?>
I need to merge two arrays. array_merge function successfully merged two of them but key value gets changed. I need the following output
Array
(
[0]=>Array(
[500] => 1
[502] => 2
[503] => 3
[504] => 5
)
)
What function can I use in php so that the following output is obtained without changing key values?
From the documentation, Example #3:
If you want to append array elements from the second array to the first array while not overwriting the elements from the first array and not re-indexing, use the + array union operator:
<?php
$array1 = array(0 => 'zero_a', 2 => 'two_a', 3 => 'three_a');
$array2 = array(1 => 'one_b', 3 => 'three_b', 4 => 'four_b');
$result = $array1 + $array2;
var_dump($result);
?>
The keys from the first array will be preserved. If an array key exists in both arrays, then the element from the first array will be used and the matching key's element from the second array will be ignored.
array(5) {
[0]=>
string(6) "zero_a"
[2]=>
string(5) "two_a"
[3]=>
string(7) "three_a"
[1]=>
string(5) "one_b"
[4]=>
string(6) "four_b"
}
Therefore, try: $a[0] + $b[0]
$a=array('0'=>array('500'=>'1','502'=>'2'));
$b=array('0'=>array('503'=>'3','504'=>'5'));
$c = $a + $b; //$c will be a merged array
see the answer for this question
Try:
$final = array();
$a=array('0'=>array('500'=>'1','502'=>'2'));
$b=array('0'=>array('503'=>'3','504'=>'5'));
foreach( $a as $key=>$each ){
$final[$key] = $each;
}
foreach( $b as $key=>$each ){
$final[$key] = $each;
}
print_r( $final );
$a=array('0'=>array('500'=>'1','502'=>'2'));
$b=array('0'=>array('503'=>'3','504'=>'5'));
$c = $a[0] + $b[0];
print_r($c);
Will print:
Array ( [500] => 1 [502] => 2 [503] => 3 [504] => 5 )
Just write :
<?php
$a = array(2=>'green', 4=>'red', 7=>'yellow',3=>'Green');
$b = array(8=>'avocado');
$d = $a+$b;
echo'<pre>'; print_r($d);
?>
out put :
Array
(
[2] => green
[4] => red
[7] => yellow
[3] => Green
[8] => avocado
)
How can I explode a string on every third semicolon (;)?
example data:
$string = 'piece1;piece2;piece3;piece4;piece5;piece6;piece7;piece8;';
Desired output:
$output[0] = 'piece1;piece2:piece3;'
$output[1] = 'piece4;piece5;piece6;'
$output[2] = 'piece7;piece8;'
I am sure you can do something slick with regular expressions, but why not just explode the each semicolor and then add them three at a time.
$tmp = explode(";", $string);
$i=0;
$j=0;
foreach($tmp as $piece) {
if(! ($i++ %3)) $j++; //increment every 3
$result[$j] .= $piece;
}
Easiest solution I can think of is:
$chunks = array_chunk(explode(';', $input), 3);
$output = array_map(create_function('$a', 'return implode(";",$a);'), $chunks);
Essentially the same solution as the other ones that explode and join again...
$tmp = explode(";", $string);
while ($tmp) {
$output[] = implode(';', array_splice($tmp, 0, 3));
};
$string = "piece1;piece2;piece3;piece4;piece5;piece6;piece7;piece8;piece9;";
preg_match_all('/([A-Za-z0-9\.]*;[A-Za-z0-9\.]*;[A-Za-z0-9\.]*;)/',$string,$matches);
print_r($matches);
Array
(
[0] => Array
(
[0] => piece1;piece2;piece3;
[1] => piece4;piece5;piece6;
[2] => piece7;piece8;piece9;
)
[1] => Array
(
[0] => piece1;piece2;piece3;
[1] => piece4;piece5;piece6;
[2] => piece7;piece8;piece9;
)
)
Maybe approach it from a different angle. Explode() it all, then combine it back in triples. Like so...
$str = "1;2;3;4;5;6;7;8;9";
$boobies = explode(";", $array);
while (!empty($boobies))
{
$foo = array();
$foo[] = array_shift($boobies);
$foo[] = array_shift($boobies);
$foo[] = array_shift($boobies);
$bar[] = implode(";", $foo) . ";";
}
print_r($bar);
Array
(
[0] => 1;2;3;
[1] => 4;5;6;
[2] => 7;8;9;
)
Here's a regex approach, which I can't say is all too good looking.
$str='';
for ($i=1; $i<20; $i++) {
$str .= "$i;";
}
$split = preg_split('/((?:[^;]*;){3})/', $str, -1,
PREG_SPLIT_NO_EMPTY | PREG_SPLIT_DELIM_CAPTURE);
Output:
Array
(
[0] => 1;2;3;
[1] => 4;5;6;
[2] => 7;8;9;
[3] => 10;11;12;
[4] => 13;14;15;
[5] => 16;17;18;
[6] => 19;
)
Another regex approach.
<?php
$string = 'piece1;piece2;piece3;piece4;piece5;piece6;piece7;piece8';
preg_match_all('/([^;]+;?){1,3}/', $string, $m, PREG_SET_ORDER);
print_r($m);
Results:
Array
(
[0] => Array
(
[0] => piece1;piece2;piece3;
[1] => piece3;
)
[1] => Array
(
[0] => piece4;piece5;piece6;
[1] => piece6;
)
[2] => Array
(
[0] => piece7;piece8
[1] => piece8
)
)
Regex Split
$test = ";2;3;4;5;6;7;8;9;10;;12;;14;15;16;17;18;19;20";
// match all groups that:
// (?<=^|;) follow the beginning of the string or a ;
// [^;]* have zero or more non ; characters
// ;? maybe a semi-colon (so we catch a single group)
// [^;]*;? again (catch second item)
// [^;]* without the trailing ; (to not capture the final ;)
preg_match_all("/(?<=^|;)[^;]*;?[^;]*;?[^;]*/", $test, $matches);
var_dump($matches[0]);
array(7) {
[0]=>
string(4) ";2;3"
[1]=>
string(5) "4;5;6"
[2]=>
string(5) "7;8;9"
[3]=>
string(6) "10;;12"
[4]=>
string(6) ";14;15"
[5]=>
string(8) "16;17;18"
[6]=>
string(5) "19;20"
}
<?php
$str = 'piece1;piece2;piece3;piece4;piece5;piece6;piece7;piece8;';
$arr = array_map(function ($arr) {
return implode(";", $arr);
}, array_chunk(explode(";", $str), 3));
var_dump($arr);
outputs
array(3) {
[0]=>
string(20) "piece1;piece2;piece3"
[1]=>
string(20) "piece4;piece5;piece6"
[2]=>
string(14) "piece7;piece8;"
}
Similar to #Sebastian's earlier answer, I recommend preg_split() with a repeated pattern. The difference is that by using a non-capturing group and appending \K to restart the fullstring match, you can spare writting the PREG_SPLIT_DELIM_CAPTURE flag.
Code: (Demo)
$string = 'piece1;piece2;piece3;piece4;piece5;piece6;piece7;piece8;';
var_export(preg_split('/(?:[^;]*;){3}\K/', $string, 0, PREG_SPLIT_NO_EMPTY));
A similar technique for splitting after every 2 things can be found here. That snippet actually writes the \K before the last space character so that the trailing space is consumed while splitting.