Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Textarea lines to array using php

Tags:

arrays

php

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);
like image 516
Sanj Avatar asked Dec 05 '25 03:12

Sanj


2 Answers

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
)
like image 173
Shafiqul Islam Avatar answered Dec 07 '25 16:12

Shafiqul Islam


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

like image 24
Anant Kumar Singh Avatar answered Dec 07 '25 17:12

Anant Kumar Singh