1

I have this array:

$age = array("Peter"=>"35", "Ben"=>"37", "Joe"=>"43");

And it prints, which is all right:

Array ( [Peter] => 35 [Ben] => 37 [Joe] => 43 )

But I want to do add values from a string, like this:

$string = '"Peter"=>"35", "Ben"=>"37", "Joe"=>"43"';
$age = array($string);

The problem is that it prints:

Array ( [0] => "Peter"=>"35", "Ben"=>"37", "Joe"=>"43" )

I don't want this:

[0] => 

And the keys are not right. It don't turn the "" to []:

Right: [Peter] => ...  
Wrong: "Peter" => ...

How can I proceed?

ecg8
  • 1,362
  • 1
  • 12
  • 16
  • Add a language tag to your question. – McGuireV10 Mar 21 '18 at 21:04
  • This is from a PHP tutorial on W3schools (https://www.w3schools.com/php/php_arrays.asp about halfway down). I think your problem is confusing strings and arrays. – ecg8 Mar 22 '18 at 00:19
  • Possible duplicate of [converting array containing keys and values into string](https://stackoverflow.com/questions/13767416/converting-array-containing-keys-and-values-into-string) – ecg8 Mar 22 '18 at 00:37
  • Hi ecg8, I've actually used this data from w3schools, but only the data entries, since I want to achieve another goal than showed there. – mova propaganda Mar 22 '18 at 01:04
  • ecg8, I tried the approach you sugested above, but it still isn't getting the expected results. I applied that logic with a few variations, but it is always printing something like this: Array ( [0] => 35 [1] => 37 [2] => 43 ). Note that the values are right, but the keys are wrong. They should be: Array ( [Peter] => 35 [Ben] => 37 [Joe] => 43 ) – mova propaganda Mar 22 '18 at 01:29
  • Simple answer: don't create the string the way you are. Just create a string of your key-value pairs delimited by something. Then have a different delimiter to separate key and value. Then explode the string into an array. Then print the array. – ecg8 Mar 22 '18 at 02:29
  • Try this answer https://stackoverflow.com/questions/5290342/php-split-delimited-string-into-key-value-pairs-associative-array – ecg8 Mar 22 '18 at 02:31
  • Wow, It worked like a charm, now it's printing: Array ( [Peter] => 35 [Ben] => 37 [Joe] => 43 ) And just by using an simple implode and parse_str. I just had to work on the input string and Voilà! It's done! Thank you ecg8. – mova propaganda Mar 22 '18 at 03:37

0 Answers0