Balakumar B
Balakumar B

Reputation: 790

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: [email protected]

Community: Test Community.';
?>

I want to convert this string to array like

Array(
   [Name] => XXXXXXXX
   [Email]=> [email protected]
   [Community] => Test Community.
)

My attempt:

$str = 'Name: XXXXXXXX Email: [email protected] Community: Test Community.';
echo "<pre>";
print_r(explode(":", $str)); 
exit; 

Upvotes: 1

Views: 100

Answers (3)

Riusma-D
Riusma-D

Reputation: 9

You can insert your elements in an array then push it in another array as below :

$array = array();

$element = array("name"=>"xxxxx", "email"=>"[email protected]", "community"=>"Test Comunity");
array_push($array, $element);

dump($array);die;

Upvotes: 0

Rakesh Jakhar
Rakesh Jakhar

Reputation: 6388

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

Upvotes: 2

MH2K9
MH2K9

Reputation: 12039

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: [email protected]

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.

Upvotes: 2

Related Questions