Professor Zoom
Professor Zoom

Reputation: 349

How to split an array and read them in PHP

I got this string that I'm getting from a table in mysql

$my_string = 40-10-10,41-20-20,42-30-30;

And i'm using this to explode it

$my_array = explode(',', $my_string); and with print_r I get this:

  Array
(
    [0] => 40-10-10
    [1] => 41-20-20
    [2] => 42-30-30
)

Now I would like to get every element of that array into another arrays, for example:

[0] => 40-10-10 should be an array like this

    Array
(
 [0] => 40
 [1] => 10
 [2] => 10
)

And then those values into variables

$v1 = 40;
$v2 = 10;
$v3 = 10;

And do the same to rest of elements an arrays, I'm stuck and I do not have idea how to achieve this, I need some help, thanks.

Upvotes: 1

Views: 50

Answers (3)

Peter Chaula
Peter Chaula

Reputation: 3711

You could try this one using array_map function which is less code for and more readable.

$my_array = explode(',', $my_string);

function get_array($str){

  return explode('-', $str);

}

$result = array_map('get_array', $my_array);

Upvotes: 0

ScaisEdge
ScaisEdge

Reputation: 133360

$my_array = explode(',', $my_string);

and then

 $my_array2 = explode('-', $my_array[0]);

$v1 = $my_array2[0];
$v2 = $my_array2[1]:
$v3 = $my_array2[2]

or like suggest by E_p

list($v1 , $v2, $v3) =  explode('-', $my_array[0]);

and repearm for the other index of $my_array (eventually with a foreach)

Upvotes: 1

Felippe Duarte
Felippe Duarte

Reputation: 15131

$my_string = 40-10-10,41-20-20,42-30-30;
$my_array = explode(',', $my_string);

$i = 1;
foreach($my_array as $m) {
    $my_numbers = explode('-', $my_string);
    foreach($my_numbers as $number) {
        ${"v".$i} = $number;
        $i++;
    }
}

Now you can do $v1, $v2, ...

Upvotes: 0

Related Questions