Home > Mobile >  How to split value from string and get in variables?
How to split value from string and get in variables?

Time:01-10

I tried to split value from string. How to do it in php?

$data = "1-2021, 2-2018, 3-2022";
Output should be,
var1= "1,2,3"
var2 = "2018,2022,2022"

CodePudding user response:

To split your items from string you need to use Explode function of php. After splitting If you want to merge them back you need to use Implode function of it.

So basicly from what you give you need to split your string first, then create 2 different arrays and add your items into it, lastly merge them back like this:

/*----- Define 2 arrays as holders ------*/
    $arr1 = array();
    $arr2 = array();

/*----- Get data and explode it ------*/
    $data = "1-2021, 2-2018, 3-2022";
    $data_exploded = explode(', ', $data);

/*----- Iterate over each item and explode them too ------*/
    foreach($data_exploded as $item){
        
        /*----- Explode here  ------*/
            $item_arr = explode('-', $item);

        /*----- Add sub items into holders ------*/
            array_push($arr1, $item_arr[0]);
            array_push($arr2, $item_arr[1]);

    }

/*----- Finally Implode your holders ------*/
    $var1 = implode(',', $arr1); // Output = "1,2,3"
    $var2 = implode(',', $arr2); // Output = "2018,2022,2022"

For further examination please check the links above.

  •  Tags:  
  • Related