I would turn it into CSV form, like so:
$string_version = implode(',', $original_array)
You can turn it back by doing:
$destination_array = explode(',', $string_version)
Answer from Teekin on Stack OverflowI would turn it into CSV form, like so:
$string_version = implode(',', $original_array)
You can turn it back by doing:
$destination_array = explode(',', $string_version)
I would turn it into a json object, with the added benefit of keeping the keys if you are using an associative array:
$stringRepresentation= json_encode($arr);
Convert array string into an array - PHP - SitePoint Forums | Web Development & Design Community
Warning: Array to string conversion in Variable method
Why does PHP convert integer-string array keys to integer?
Javascript Array Is Getting Converted To A String in PHP File?
As I noted in the comment to you, your example string is invalid. This example shows a valid string version of json. Use json_decode, with the 2nd parameter set to true to turn the embedded objects into array elements.
You will get an embedded array of arrays, but you can easily flatten that using the spread operator (...) with array_merge.
<?php
$string = '[{"006":"BASIC"},{"007":"ADV"}]';
$r = json_decode($string, true);
$r = array_merge(...$r);
print_r($r);
Outputs:
Array
(
[006] => BASIC
[007] => ADV
)
$string = '[{"006":"BASIC"}, {"007":"ADV"}, {"008":"ADV"}, {"009":"SUPER"}]';
var_dump(json_decode($string, true));
die;
Of if you need to join 2 arrays then you can first decode them and then merge them.
$stringOne = '[{"006":"BASIC"}, {"007":"ADV"}]';
$stringTwo = '[{"008":"ADV"}, {"009":"SUPER"}]';
$finalArray = array_merge(json_decode($stringOne, true), json_decode($stringTwo, true));
var_dump(json_encode($finalArray));
die;
I have an issue I know how to solve but I am curios to why I need to make this extra step to make it work.
I have the following code:
foreach ($routes as $key => $value) {
$router->$value["method"]($value["path"], "something");
}
the value inside the array $value["method"] is a string that maps to the method names on the class Router
If I run this code I get the error:Warning: Array to string conversion
If I change the code to the following, it works:
foreach ($routes as $key => $value) {
$method = $value["method"];
$router->$method($value["path"], "something");
}The solution is to extract the value from the array before using it as a variable method. It seems that the PHP interpreter doesn't retrieve the value from the array when it's used directly within a variable method, resulting in an 'array to string' error. Extracting the value first resolves this issue.
anyone could clarify?
Example: https://3v4l.org/RmAXf
It is clearly documented - I guess I just never paid close enough attention before: https://www.php.net/manual/en/language.types.array.php#language.types.array.syntax
But I am wondering if anybody knows why? Was this an intentional decision?