Reputation: 141
I have a php variable that contain value of textarea as below.
Name:Jay
Email:[email protected]
Contact:9876541230
Now I want this lines to in array as below.
Array
(
[Name] =>Jay
[Email] =>[email protected]
[Contact] =>9876541230
)
I tried below,but won't worked:-
$test=explode("<br />", $text);
print_r($test);
Upvotes: 3
Views: 6140
Reputation: 5690
you can try this code using php built in PHP_EOL
but there is little problem about array index so i am fixed it
<?php
$text = 'Name:Jay
Email:[email protected]
Contact:9876541230';
$array_data = explode(PHP_EOL, $text);
$final_data = array();
foreach ($array_data as $data){
$format_data = explode(':',$data);
$final_data[trim($format_data[0])] = trim($format_data[1]);
}
echo "<pre>";
print_r($final_data);
and output is :
Array
(
[Name] => Jay
[Email] => [email protected]
[Contact] => 9876541230
)
Upvotes: 6
Reputation: 72299
Easiest way to do :-
$textarea_array = array_map('trim',explode("\n", $textarea_value)); // to remove extra spaces from each value of array
print_r($textarea_array);
$final_array = array();
foreach($textarea_array as $textarea_arr){
$exploded_array = explode(':',$textarea_arr);
$final_array[trim($exploded_array[0])] = trim($exploded_array[1]);
}
print_r($final_array);
Output:- https://eval.in/846556
Upvotes: 5
Reputation: 462
I think you need create 3 input:text, and parse them, because if you write down this value in text area can make a mistake, when write key. Otherwise split a string into an array, and after create new array where key will be odd value and the values will be even values old array
Upvotes: 0
Reputation: 141
This also works for me.
$convert_to_array = explode('<br/>', $my_string);
for($i=0; $i < count($convert_to_array ); $i++)
{
$key_value = explode(':', $convert_to_array [$i]);
$end_array[$key_value [0]] = $key_value [1];
}
print_r($end_array); ?>
Upvotes: 0