How to transform this array into an array of 4 indexes?

Asked

Viewed 75 times

-5

Array
    (
        [0] => Camaquã,Cavalhada,Cristal,Hípica
    )

I need to transform the array above in an array of 4 indexes as seen below.

Array
    (
        [0] => Camaquã
        [1] => Cavalhada
        [2] => Cristal
        [3] => Hípica
   )

1 answer

4


This is easy, use the famous explode

<?php    

$array = array('Camaquã,Cavalhada,Cristal,Hípica');  // Possivelmente está assim.
$stringAux = rtrim($array['0'],','); // isto irá remover a ultima "," caso exista "Hípica,"
$array_resultado = explode(',', $stringAux); // Divide cada ","

var_dump($array_resultado);

// RESULTADO (VAR_DUMP):  
//array(4) {
//  [0]=>
//  string(8) "Camaquã"
//  [1]=>
//  string(9) "Cavalhada"
//  [2]=>
//  string(7) "Cristal"
//  [3]=>
//  string(7) "Hípica"
//}

Always use var_dump to see what the variable is loading, it will be much easier to learn/develop, logically remove when publishing it.

Testing this here!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.