Put string into key value array - php

Hi I got the following string:
info:infotext,
dimensions:dimensionstext
and i need to put these values into an array in PHP. What is the regex function to put these into an array. I studied the regex codes but it's kinds confusing to me.
I want to put the info as the key and he infotext as the value into an array like this:
Array {
[info] => infotext
[dimensions] => dimensionstext
}

Demo here
<?php
$string ='info:infotext,
dimensions:dimensionstext';
$array = array_map(function($v){return explode(':', trim($v));}, explode(',', $string));
foreach($array as $v)
{
$o[$v[0]] = $v[1];
}
print_r($o);

You can use array_chunk and array_combine
<?php
$input = 'info:infotext,
dimensions:dimensionstext';
$chunks = array_chunk(preg_split('/(:|,)/', $input), 2);
$result = array_combine(array_column($chunks, 0), array_column($chunks, 1));
print_r($result);
http://ideone.com/dRtref

Related

How to match and replace one array values to another array keys if they both start with the same letters?

I have two arrays:
$array_one = array('AA','BB','CC');
And:
$replacement_keys = array
(
""=>null,
"BFC"=>'john',
"ASD"=>'sara',
"CSD"=>'garry'
);
So far I've tried
array_combine and to make a loop and try to search for values but can't really find a solution to match the keys of the second array with the values of the first one and replace it.
My goal is to make a final output:
$new_array = array
(
''=>null,
'BB' => 'john',
'AA' => 'sara',
'CC' => 'garry'
);
In other words to find a matching first letter and than replace the key with the value of the first array.
Any and all help will be highly appreciated.
Here is a solution keeping both $replacement_keys and $array_one intact
$tempArray = array_map(function($value){return substr($value,0,1);}, $array_one);
//we will get an array with only the first characters
$new_array = [];
foreach($replacement_keys as $key => $replacement_key) {
$index = array_search(substr($key, 0, 1), $tempArray);
if ($index !== false) {
$new_array[$array_one[$index]] = $replacement_key;
} else {
$new_array[$key] = $replacement_key;
}
}
Here is a link https://3v4l.org/fuHSu
You can approach like this by using foreach with in_array
$a1 = array('AA','BB','CC');
$a2 = array(""=>null,"BFC"=>'john',"ASD"=>'sara',"CSD"=>'garry');
$r = [];
foreach($a2 as $k => $v){
$split = str_split($k)[0];
$split .= $split;
in_array($split, $a1) ? ($r[$split] = $v) : ($r[$k] = $v);
}
Working example :- https://3v4l.org/ffRWY

Pass comma separated key string and get value of array according to key in PHP

I am trying to get value from array and pass only comma separated key string and get same output without. Is it possible without using foreach statement. Please suggest me.
<?php
$str = "1,2,3";
$array = array("1"=>"apple", "2"=>"banana", "3"=>"orange");
$keyarray = explode(",",$str);
$valArr = array();
foreach($keyarray as $key){
$valArr[] = $array[$key];
}
echo $valStr = implode(",", $valArr);
?>
Output : apple,banana,orange
Use array_intersect_key
$str = "1,2,3";
$array = array("1"=>"apple", "2"=>"banana", "3"=>"orange");
$keyarray = explode(",",$str);
echo implode(",", array_intersect_key($array, array_flip($keyarray)));
https://3v4l.org/gmcON
One liner:
echo implode(",", array_intersect_key($array, array_flip(explode(",",$str))));
A mess to read but a comment above can explain what it does.
It means you don't need the $keyarray
Suggestion : Use separate row for each value, to better operation. Although you have created right code to get from Comma sparate key to Value from array, but If you need it without any loop, PHP has some inbuilt functions like array_insersect , array_flip to same output
$str = "1,2";
$arr1 = ["1"=>"test1","2"=>"test2","3"=>"test3"];
$arr2 = explode(",",$str);
echo implode(", ",array_flip(array_intersect(array_flip($arr1),$arr2)));
Live demo
you can try using array_filter:
$str = "1,2,3";
$array = array("1"=>"apple", "2"=>"banana", "3"=>"orange");
$keyarray = explode(",",$str);
$filtered = array_filter($array, function($v,$k) use($keyarray){
return in_array($k, $keyarray);
},ARRAY_FILTER_USE_BOTH);
print_r($filtered);
OUTPUT
Array
(
[1] => apple
[2] => banana
[3] => orange
)
Another way could be using array_map():
echo $valStr = implode(",", array_map(function ($i) use ($array) { return $array[$i]; }, explode(",", $str)));
Read it from bottom to top:
echo $valStr = implode( // 3. glue values
",",
array_map( // 2. replace integers by fruits
function ($i) use ($array) {
return $array[$i];
},
explode(",", $str) // 1. Split values
)
);

Filter a string in PHP

I'm looking to get an array of ID's from the following string.
[vc_gallery type="flexslider_fade" interval="3" images="3057,2141,234" onclick="link_image" custom_links_target="_self" img_size="large"]
Ideally, i'd like to look at this string and get an array of the INT values within images. e.g.
array("3057", "2141", "234");
find images value and explode it to receive array
$str = '[vc_gallery type="flexslider_fade" interval="3" images="3057,2141,234" onclick="link_image" custom_links_target="_self" img_size="large"]';
if (preg_match('/images\s*=\s*\"([^\"]+)\"/', $str, $m)) {
$res = explode(',', $m[1]);
print_r($res);
}
Another solution using explode and strpos functions:
$str = '[vc_gallery type="flexslider_fade" interval="3" images="3057,2141,234" onclick="link_image" custom_links_target="_self" img_size="large"]';
foreach (explode(" ", $str) as $v) {
if (strpos($v, "images=") === 0) {
$result = explode(",", explode('"', $v)[1]);
break; // avoids redundant iterations
}
}
print_r($result);
The output:
Array
(
[0] => 3057
[1] => 2141
[2] => 234
)

getting all the values in an array except the last one

I have this right now :
$s = preg_split('/\s+/', $q);
$k = end($s);
What I want now is to get all the values in the array $k[] except the last one, and join them in a new string. So basically if the array was :
0 => Hello
1 => World
2 => text
I would get Hello World
Use array_slice and implode:
$k = array( "Hello", "World", "text" );
$sliced = array_slice($k, 0, -1); // array ( "Hello", "World" )
$string = implode(" ", $sliced); // "Hello World";
If you can modify the array:
array_pop($k);
$string = join(' ', $k);
array_pop() pops and returns the last value of the array, shortening the array by one element. If array is empty (or is not an array), NULL will be returned.
Source
Use array_slice($array) to get a subset of any array.
For everything without the last item I believe it is
$return = array_slice($array, 0, count($array)-1, true);
Testcase http://codepad.org/fyHHX5Us
Something like this:
<?php
$array = array('Hello', 'World', 'text');
$new_array = array_slice($array,0,-1);
echo implode(' ',$new_array);
?>
Example

Removing all instances of items from array

I have an array which may have duplicate values
$array1 = [value19, value16, value17, value16, value16]
I'm looking for an efficient little PHP function that could accept either an array or a string (whichever makes it easier)
$array2 = ["value1", "value16", "value17"];
or
$string2 = "value1 value16 value17";
and removes each item in array2 or string2 from array1.
The right output for this example would be:
$array1 = [value19]
For those more experienced with PHP, is something like this available in PHP?
you're looking for array_diff
$array1 = array('19','16','17','16','16');
$array2 = array('1','16','17');
print_r(array_diff($array1,$array2));
Array ( [0] => 19 )
For the string version to work, use explode.
Like this:
function arraySubtract($one, $two) {
// If string => convert to array
$two = (is_string($two))? explode(' ',$two) : $two;
$res = array();
foreach (array_diff($one, $two) as $key => $val) {
array_push($res, $val);
}
return $res;
}
This allso returns an array with key = 0....n with no gaps
Test with this:
echo '<pre>';
print_r(arraySubtract(array(1,2,3,4,5,6,7), array(1,3,7)));
print_r(arraySubtract(array(1,2,3,4,5,6,7), "1 3 7"));
print_r(arraySubtract(array("val1","val2","val3","val4","val5","val6"), array("val1","val3","val6")));
print_r(arraySubtract(array("val1","val2","val3","val4","val5","val6"), "val1 val3 val6"));
echo '</pre>';

Categories