Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to make a string into an array in php

Tags:

arrays

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..

like image 419
Suganya Rajasekar Avatar asked Feb 27 '26 16:02

Suganya Rajasekar


2 Answers

Try:

$str = "food_item => 'Butter Croissant',food_id => '1',quantity => '1',price => '140'";
$mainArray = explode(",",$str);
$newArray = array();
foreach($mainArray as $main) {
  $innerArray = explode("=>",$main);
  $newArray[trim($innerArray[0])] = trim($innerArray[1]);
}

Output:

Array
(
    [food_item] => 'Butter Croissant'
    [food_id] => '1'
    [quantity] => '1'
    [price] => '140'
)
like image 153
Jayesh Chitroda Avatar answered Mar 02 '26 05:03

Jayesh Chitroda


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

like image 38
Anant Kumar Singh Avatar answered Mar 02 '26 06:03

Anant Kumar Singh



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!