How to convert String Array to php Array? - php

How to convert Sting Array to PHP Array?
"['a'=>'value one','key2'=>'value two']"
to
$data=['a'=>'value one','key2'=>'value two'];
Please let me know if anyone knows of any solution
I want to take array input via textarea. And I want to convert that to a PHP array.
When I'm through textarea
['a'=>'value one','key2'=>'value two']
This is happening after submitting the from
"['a'=>'value one','key2'=>'value two']"
Now how do I convert from this to PHP Array?

Assuming you are not allowing multi dimensional arrays, this will work:
$stringArray = "['a'=>'value one','key2'=>'value two']";
$array = array();
$trimmedStringArray = trim( $stringArray, '[]' );
$splitStringArray = explode( ',', $trimmedStringArray );
foreach( $splitStringArray as $nameValuePair ){
list( $key, $value ) = explode( '=>', $nameValuePair );
$array[$key] = $value;
}
Output:
Array
(
['a'] => 'value one'
['key2'] => 'value two'
)
You will probably want to do some error checking to make sure the input is in the correct format before you process the input.

Extremely unsafe version using eval():
<?php
$a = "['a'=>'value one','key2'=>'value two']";
eval('$b = '.$a.';');
print('<pre>');
print_r($b);
Use only when you are sure, that other people can't use your textarea input!
Using replacements to convert this to json is a much better option for public forms. Additionally, if you use this at your work, you probably would get fired :)
With syntax error catch:
<?php
$a = "['a'=>'value one','key2'=>'value two'dsbfbtrg]";
try {
eval('$b = '.$a.';');
} catch (ParseError $e) {
print('Bad syntax');
die();
// or do something about the error
}
print('<pre>');
print_r($b);

Another option:
<?php
$string = "['a'=>'value one','key2'=>'value two']";
$find = ["'", "=>", "[", "]"];
$replace = ["\"", ":", "{", "}"];
$string = str_replace($find, $replace, $string);
$array = json_decode($string, true);
var_dump($array);
?>

Related

Convert PHP string to custom formatted array for function

I need help converting a PHP string into an array that is formatted to work within a PHP function. I have a string like this:
$string = '11111, 22222, 33333';
I need this string to explode into an array that looks like this:
array("11111"=>"11111","22222"=>"22222","33333"=>"33333")';
The function looks like this:
function callback_numbers() {
$numbers = array(
"11111"=>"11111",
"22222"=>"22222",
"33333"=>"33333",
);
return $numbers;
}
I can't get the array to appear correctly when inside the function so that the array is returned correctly and the function works. When I print_t $numbers it looks ok but it won't work when I return $numbers.
Try this. Yoy can split using , but after you need to trim as there might be spaces between your numbers
$string = '11111, 22222, 33333';
$numbers = explode(',', $string );
$result = [];
foreach ($numbers as $item) {
$item = trim( $item );
$result [ $item ] = $item;
}
var_dump($result);

How to convert a string to associate array in php?

I have a string with a line break and spaces in the following format.
<?php
$str = 'Name: XXXXXXXX
Email: XXXX#sample.com
Community: Test Community.';
?>
I want to convert this string to array like
Array(
[Name] => XXXXXXXX
[Email]=> XXXX#sample.com
[Community] => Test Community.
)
My attempt:
$str = 'Name: XXXXXXXX Email: XXXX#sample.com Community: Test Community.';
echo "<pre>";
print_r(explode(":", $str));
exit;
First split the string using the pattern \n+. Then make an iteration over the array using array_reduce() got after splitting the string. In every cycle of the iteration explode the string ane prepare. your expected format.
Code example:
$str = 'Name: XXXXXXXX
Email: XXXX#sample.com
Community: Test Community.';
$elm = preg_split('/\n+/', $str);
$data = array_reduce($elm, function ($old, $new) {
$key_value = explode(':', $new);
$old[$key_value[0]] = $key_value[1];
return $old;
}, []);
print_r($data);
Working demo.
You can use array_filter with array_walk & explode
$c = array_filter(explode('
', $str));
$r = [];
array_walk($c, function($v, $k) use (&$r){
$arr = explode(':', $v);
$r[$arr[0]] = $arr[1];
});
Working example : https://3v4l.org/fgKnE
You can insert your elements in an array then push it in another array as below :
$array = array();
$element = array("name"=>"xxxxx", "email"=>"xxx#sample.com", "community"=>"Test Comunity");
array_push($array, $element);
dump($array);die;

How to explode string into array with index in php? [duplicate]

This question already has answers here:
Explode a string to associative array without using loops? [duplicate]
(10 answers)
Closed 7 months ago.
I have a PHP string separated by characters like this :
$str = "var1,'Hello'|var2,'World'|";
I use explode function and split my string in array like this :
$sub_str = explode("|", $str);
and it returns:
$substr[0] = "var1,'hello'";
$substr[1] = "var2,'world'";
Is there any way to explode $substr in array with this condition:
first part of $substr is array index and second part of $substr is variable?
example :
$new_substr = array();
$new_substr["var1"] = 'hello';
$new_substr["var2"] = 'world';
and when I called my $new_substr it return just result ?
example :
echo $new_substr["var1"];
and return : hello
try this code:
$str = "var1,'Hello'|var2,'World'|";
$sub_str = explode("|", $str);
$array = [];
foreach ($sub_str as $string) {
$data = explode(',', $string);
if(isset($data[0]) && !empty($data[0])){
$array[$data[0]] = $data[1];
}
}
You can do this using preg_match_all to extract the keys and values, then using array_combine to put them together:
$str = "var1,'Hello'|var2,'World'|";
preg_match_all('/(?:^|\|)([^,]+),([^\|]+(?=\||$))/', $str, $matches);
$new_substr = array_combine($matches[1], $matches[2]);
print_r($new_substr);
Output:
Array (
[var1] => 'Hello'
[var2] => 'World'
)
Demo on 3v4l.org
You can do it with explode(), str_replace() functions.
The Steps are simple:
1) Split the string into two segments with |, this will form an array with two elements.
2) Loop over the splitted array.
3) Replace single quotes as not required.
4) Replace the foreach current element with comma (,)
5) Now, we have keys and values separated.
6) Append it to an array.
7) Enjoy!!!
Code:
<?php
$string = "var1,'Hello'|var2,'World'|";
$finalArray = array();
$asArr = explode('|', $string );
$find = ["'",];
$replace = [''];
foreach( $asArr as $val ){
$val = str_replace($find, $replace, $val);
$tmp = explode( ',', $val );
if (! empty($tmp[0]) && ! empty($tmp[1])) {
$finalArray[ $tmp[0] ] = $tmp[1];
}
}
echo '<pre>';print_r($finalArray);echo '</pre>';
Output:
Array
(
[var1] => Hello
[var2] => World
)
See it live:
Try this code:
$str = "var1,'Hello'|var2,'World'|";
$sub_str = explode("|", $str);
$new_str = array();
foreach ( $sub_str as $row ) {
$test_str = explode( ',', $row );
if ( 2 == count( $test_str ) ) {
$new_str[$test_str[0]] = str_replace("'", "", $test_str[1] );
}
}
print $new_str['var1'] . ' ' . $new_str['var2'];
Just exploding your $sub_str with the comma in a loop and replacing single quote from the value to provide the expected result.

php call array from string

I have a string that contains elements from array.
$str = '[some][string]';
$array = array();
How can I get the value of $array['some']['string'] using $str?
This will work for any number of keys:
$keys = explode('][', substr($str, 1, -1));
$value = $array;
foreach($keys as $key)
$value = $value[$key];
echo $value
You can do so by using eval, don't know if your comfortable with it:
$array['some']['string'] = 'test';
$str = '[some][string]';
$code = sprintf('return $array%s;', str_replace(array('[',']'), array('[\'', '\']'), $str));
$value = eval($code);
echo $value; # test
However eval is not always the right tool because well, it shows most often that you have a design flaw when you need to use it.
Another example if you need to write access to the array item, you can do the following:
$array['some']['string'] = 'test';
$str = '[some][string]';
$path = explode('][', substr($str, 1, -1));
$value = &$array;
foreach($path as $segment)
{
$value = &$value[$segment];
}
echo $value;
$value = 'changed';
print_r($array);
This is actually the same principle as in Eric's answer but referencing the variable.
// trim the start and end brackets
$str = trim($str, '[]');
// explode the keys into an array
$keys = explode('][', $str);
// reference the array using the stored keys
$value = $array[$keys[0][$keys[1]];
I think regexp should do the trick better:
$array['some']['string'] = 'test';
$str = '[some][string]';
if (preg_match('/\[(?<key1>\w+)\]\[(?<key2>\w+)\]/', $str, $keys))
{
if (isset($array[$keys['key1']][$keys['key2']]))
echo $array[$keys['key1']][$keys['key2']]; // do what you need
}
But I would think twice before dealing with arrays your way :D

Replace string in an array with PHP

How can I replace a sub string with some other string for all items of an array in PHP?
I don't want to use a loop to do it. Is there a predefined function in PHP that does exactly that?
How can I do that on keys of array?
Why not just use str_replace without a loop?
$array = array('foobar', 'foobaz');
$out = str_replace('foo', 'hello', $array);
$array = array_map(
function($str) {
return str_replace('foo', 'bar', $str);
},
$array
);
But array_map is just a hidden loop. Why not use a real one?
foreach ($array as &$str) {
$str = str_replace('foo', 'bar', $str);
}
That's much easier.
This is a very good idea that I found and used successfully:
function str_replace_json($search, $replace, $subject)
{
return json_decode(str_replace($search, $replace, json_encode($subject)), true);
}
It is good also for multidimensional arrays.
If you change the "true" to "false" then it will return an object instead of an associative array.
Source: Codelinks
I am not sure how efficient this is, but I wanted to replace strings in a big multidimensional array and did not want to loop through all items as the array structure is pretty dynamic.
I first json_encode the array into a string.
Replace all the strings I want (need to use preg_replace if there are non-English characters that get encoded by json_encode).
json_decode to get the array back.
function my_replace_array($array,$key,$val){
for($i=0;$i<count($array);$i++){
if(is_array($array[$i])){
$array[$i] = my_replace_array($array[$i],$key,$val);
}else{
$array[$i]=str_replace($key,$val,$array[$i]);
}
}
return $array;
}
With array_walk_recursive()
function replace_array_recursive( string $needle, string $replace, array &$haystack ){
array_walk_recursive($haystack,
function (&$item, $key, $data){
$item = str_replace( $data['needle'], $data['replace'], $item );
return $item;
},
[ 'needle' => $needle, 'replace' => $replace ]
);
}
$base = array('citrus' => array( "orange") , 'berries' => array("blackberry", "raspberry"), );
$replacements = array('citrus' => array('pineapple'), 'berries' => array('blueberry'));
$basket = array_replace_recursive($base, $replacements);
$basket = array_replace($base, $replacements);

Categories