Array assignment in variable

2

Is there a proper way to do this highlighted code snippet?

$numeros = range(0, 9);
shuffle($numeros);
$id = array_slice($numeros, 1, 9);

$mult = $id[0].$id[1].$id[2].$id[3].$id[4].$id[5].$id[6].$id[7].$id[8];

echo $mult;

In other words, my intent is to transform an array into a simple variable for later use, in this case

$mult = $id[0].$id[1].$id[2].$id[3].$id[4].$id[5].$id[6].$id[7].$id[8];

Could it be done in a more professional way?

    
asked by anonymous 02.02.2015 / 23:24

3 answers

2

I think this is what you want:

$numeros = range(0, 9);
shuffle($numeros);
$id = array_slice($numeros, 1, 9);
$mult = "";
for ($i = 0; $i < 9; $i++) {
    $mult .= $id[$i];
}

This way you are doing the variable repeat nine times automatically. You are creating a loop of repetition. So there in% w / o% you are counting from 0 to 9, incrementing one by one, then in each pass through the loop it takes an index other than the for according to the loop count variable. Each time it passes it, it concatenates the new array element to the variable that will receive the final result.

The result is exactly the same as what you did.

Documentation for array and for for more references and study.

    
02.02.2015 / 23:30
3

Another way to convert an array to a string is to use implode , the first argument is array a to be converted, the second would be a delimiter that would be between the array items, in which case you can use nothing ( '' ) so the generated string will be a 10 digit number.

<?php
$numeros = range(0, 9);
$str_numero = implode($numeros, '');
echo $str_numero;

phpfiddle - example

    
02.02.2015 / 23:57
-1

You can use the serialize() function and the unserialize() function, among others. (JSON for example)

Link to the documentation for the serialize function

Link to function documentation unserialize

PS: I know it's not the case, it's just a more comprehensive alternative.

    
24.02.2016 / 03:11