Hello, I have a sequence of numbers in a string, example: 1; 2; 3; 4; 5; 6. I would like to take each number and store them in an array of integers in PHP. Anyone have a suggestion?
Hello, I have a sequence of numbers in a string, example: 1; 2; 3; 4; 5; 6. I would like to take each number and store them in an array of integers in PHP. Anyone have a suggestion?
Just use the native function explode
:
array explode ( string $delimiter , string $string [, int $limit ] )
The first parameter is the delimiter, that is, the expression you want to use as a reference for splitting your text and the second parameter is the text itself. The third parameter is optional and, if set, limits the number of separations made.
For your example:
$lista = explode(";", "1;2;3;4;5;6");
print_r($lista);
The result is:
Array
(
[0] => 1
[1] => 2
[2] => 3
[3] => 4
[4] => 5
[5] => 6
)
Related questions:
The command for this is explode
as stated above very clearly.
Follow the link for reference on the PHP website: link
And another example of a little more detailed use:
<?php
//string que recebe os números
$_string = "1;2;3;4;5;6";<br />
//O explode define qual vai ser o caractere a ser usado na divisão da string e a variável $converte_array recebe as substrings resultantes desta divisão.
$converte_array = explode(";",$_string );
//como exibir esses resultados:
echo $converte_array[0]; //retorna 1
echo $converte_array[1]; //retorna 2
echo $converte_array[2]; //retorna 3
echo $converte_array[3]; //retorna 4
echo $converte_array[4]; //retorna 5
echo $converte_array[5]; //retorna 6
// sem se esquecer que arrays em php assim como em outras linguagens se iniciam em 0 e não em 1