-1

I use laravel. And then when from submitted, it pass value as array.

My question is, how i can split the value? I want number before '-' and after '-'.

enter image description here

I want just like below:

enter image description here

and

enter image description here

My code just like below

   $form = $request->all();
   $emelto = $form['emelto'];
   $split = explode('-', $emelto );

but it shows error

explode() expects parameter 2 to be string, array given

Please someone can help me.

Nurul
  • 95
  • 1
  • 9

3 Answers3

1
  • Explode each individual string as you tried.
  • Insert each number in it's respective column index in result.

Snippet:

<?php

$emelto = [
    '4-2',
    '11-5'
];

$data = [];
foreach($emelto as $str){
    foreach(explode('-',$str) as $index => $s){
        $data[$index] = $data[$index] ?? [];// assuming your PHP version supports ??
        $data[$index][] = $s;
    }
}

print_r($data);
nice_dev
  • 17,053
  • 2
  • 21
  • 35
1

You can use

$array1 = array();
$array2 = array();
foreach($request->emelto as $val){
    $dataArray = explode('-', $val);
    $array1[] = $dataArray[0];
    $array2[] = $dataArray[1];
}
0

$emelto is an array and you are passing it to explode. You have to pass it like $emelto[0].

You should update your code with the below one.

<?php
$form = $request->all();
$emelto = $form['emelto'];
$array1 = explode('-', $emelto[0] );
$array2 = explode('-', $emelto[1] );

$array3 = array();
array_push($array3, $array1[0]);
array_push($array3, $array2[0]);

$array4 = array();
array_push($array4, $array1[1]);
array_push($array4, $array2[2]);
?>
John Doe
  • 1,401
  • 1
  • 3
  • 14
  • Btw, thanks for the answer. But its not working. It gives me [4,2]. I want 1st number. [4,11] – Nurul Apr 28 '21 at 04:04