Suganya Rajasekar Suganya Rajasekar - 4 months ago 8
PHP Question

How to make a string into an array in php

I'm having a

string
like this..

food_item => 'Butter Croissant',food_id => '1',quantity => '1',price => '140'


I tried explode option

But I'm getting an
array
like this

Array
(
[0] => 'food_item' => 'Butter Croissant'
[1] => 'food_id' => '1'
[2] => 'quantity' => '1'
[3] => 'price' => '140'
)


But I should need to make it as an
array
like as follows,

Array
(
[food_item] => 'Butter Croissant'
[food_id] => '1'
[quantity] => '1'
[price] => '140'
)


how should I do this,Someone please help me..

Thank you in advance..

Answer

You can do it like below:-

<?php
$string = "food_item => 'Butter Croissant',food_id => '1',quantity => '1',price => '140'"; // original string

$first_array = explode(',',$string); // your first explode with `,`

$final_array = array(); // create a new empty array

foreach($first_array as $arr){ // iterate over previously exploded array
    $data = explode('=>',$arr); // now explode the value again with `=>`
    $final_array[trim($data[0])] = trim($data[1]);  // add it to final array in the form of key=>value pair
}

echo "<pre/>";print_r($final_array);

Output:-https://eval.in/609356

Note:- this is easiest stuff to do and to understand also.thanks