duong khang
duong khang

Reputation: 352

Foreach loop always add first character of string to the array

I am making a function that can help me to cast the string to array, but that strange when the function always add first character to the array. Thank at first and this is code i used in function:

   $string = '0:009987;1:12312;2:45231;3:00985;3:10923;4:11253;4:62341;4:01102;4:58710;4:10102;4:87093;4:12034;5:9801;6:1092;6:4305;6:1090;7:450;8:34';
$explodedString = explode(';', $string);

//var_dump($explodedString);
$takeArray = array();
$counti = 0;
foreach($explodedString as $exploded){
 $secondExp = explode(':', $exploded);
 var_dump($secondExp);
 if(isset($takeArray[$secondExp[0]])){
  $takeArray[$secondExp[0]][$counti] = $secondExp[1];
 }else{
  $takeArray[$secondExp[0]] = $secondExp[1];
 }
 $counti++;
}

var_dump($takeArray);

This is current output of this code:

array (size=9)


0 => string '009987' (length=6)
  1 => string '12312' (length=5)
  2 => string '45231' (length=5)
  3 => string '00981' (length=5)
  4 => string '11253 605181' (length=12)
  5 => string '9801' (length=4)
  6 => string '1092          41' (length=16)
  7 => string '450' (length=3)
  8 => string '34' (length=2)

Looking into row 4 you will see the string: '605181', this string come from the first character of each value belong to 4. But i need an output array like this:

[0] => {'009987'},
....
[4] => { '11253', '62341', ...., },
....

Please help me.

Upvotes: 2

Views: 857

Answers (3)

Daniel Centore
Daniel Centore

Reputation: 3349

$string = '0:009987;1:12312;2:45231;3:00985;3:10923;4:11253;4:62341;4:01102;4:58710;4:10102;4:87093;4:12034;5:9801;6:1092;6:4305;6:1090;7:450;8:34';
$explodedString = explode(';', $string);

$takeArray = array();
foreach($explodedString as $exploded)
{
    $secondExp = explode(':', $exploded);
    $takeArray[$secondExp[0]][] = $secondExp[1];
}

var_dump($takeArray);

Upvotes: 0

Cyriaque C
Cyriaque C

Reputation: 36

You only need to do the following :

$takeArray = array();
foreach($explodedString as $exploded) {
  $secondExp = explode(':', $exploded);
  $takeArray[(int)$secondExp[0]][] = $secondExp[1];
}

Upvotes: 1

John Bupit
John Bupit

Reputation: 10618

I'm not sure why you need $counti. All you need to do is, initialize the $takeArray[$n] if it doesn't exists, and push a new value to it. Something like this:

if(!isset($takeArray[$secondExp[0]])) {
    // Initialize the array
    $takeArray[$secondExp[0]] = array();
}

// Push the new value to the array
$takeArray[$secondExp[0]][] = $secondExp[1];

Upvotes: 2

Related Questions