I have a numerous textareas which should be filled with the words or phrases that would be separated by new line (press enter).
So, on my html page I got something like this:
<textarea name="txt[1]" rows="6" cols="30"></textarea>
<textarea name="txt[2]" rows="6" cols="30"></textarea>
// and so on...
Therefore, I got a php script that should catch the values of the textareas and put it in the array. The text from the first textarea should be in one array, etc...
Is this kind of construction possible? One array? More arrays?
For example: I have a similar text:
Textarea 1:
This is the new line 1
This is the new line 2
This is the new line 3
Textarea 2:
This is the new line 7
This is the new line 8
So, the arrays should be like:
myarr[1] = ["This is the new line 1","This is the new line 2","This is the new line 3"];
myarr[2] = ["This is the new line 7","This is the new line 8"];
So, if I have myarr[2][1] = it will be: This is the new line 8
Is it possible to create in some loop or anything? Or maybe put it in one array somehow?
Instead of naming the text area txt[1] txt[2] etc..
, name them txt1 txt2 etc...
<?php
if(isset($_POST['submit'])){ //On submit
$i = 1; //index of every text area. EX: txt1, txt2
$result = array();
while(isset($_POST["txt$i"])){
$result[$i-1] = array(); //initialize the array starting from $result[0], $result[1] ...
$result[$i-1] = explode("
",$_POST["txt$i"]);//put every line as a separate element
$i++; //increment i to go the next text area
}
//print the result array created
print_r($result);
}
PHP treats all txt[*]
elements as one request parameter of array
type.
So your script may look like this:
if (isset($_REQUEST['txt']) && is_array($arr = $_REQUEST['txt']) {
$myarr = array_map(
function ($v) {
return explode("
", str_replace("
", "
", $v));
},
array_values($arr)
);
}
You can use the explode function and detect the newline character ( " ") to break the content of each textarea as an array
Here is a sample script:
<form method="POST">
<textarea name="txt[1]" rows="6" cols="30"></textarea> <br/>
<textarea name="txt[2]" rows="6" cols="30"></textarea> <br/>
<input type="submit" />
</form>
<?php
if( $_SERVER['REQUEST_METHOD'] == 'POST' ){
$txt = $_POST['txt'];
$txt[1] = explode( "
" , $txt[1] );
$txt[2] = explode( "
", $txt[2] );
print_r( $txt );
}
?>
The resulting array will be something like this:
Array
(
[1] => Array
(
[0] => aaa bbb ccc
[1] => ddd eee fff
)
[2] => Array
(
[0] => www qqq ttt
[1] => bbb mmm kkk
)
)