Foreach List does not recognize array

Asked

Viewed 88 times

1

I’m using PHP. I pass the values by _POST, and I have a string, which I turned into an array:

By the _POST method it arrives like this:

[1v4],,,,[5v3],,,[8v]

Remove excess commas, pull the v separator and turn it into an array with the commands below:

$valors = $_POST['valors'];
$array = str_replace(",","",$valors);
$array1 = str_replace("v",",",$array);
$array2 = str_replace("]","],-",$array1);
$arr = explode('-', $array2);

Var_dump output of $arr variable:

array(4) { 
[0]=> string(6) "[1,4],"
[1]=> string(6) "[5,3],"
[2]=> string(5) "[8,],"
[3]=> string(0) "" 
}

Output by simple foreach:

[1,4],
[5,3],
[8,],

But when I try to make a foreach list, the values of the variables A and B return null:

foreach ($arr as list($a, $b)) {
    echo "A: $a; B: $b\n<br>";
}

And I don’t know what else to do to separate the two values in the variables...

  • To answer you safely we need the string which is converting and the conversion method or function.

  • 1

    Thank you for the reply, requested data added.

  • 3

    The problem is in the method that generates the array $arr. Those elements of $arr: [1,4],, [5,3], and [8,], were mistakenly generated as strings and not arrays. list() only works on array. So every iteration of foreach ($arr as list($a, $b)) he’s iterating on a string of $arr therefore $aand $b are void.

  • I suggest you clean the array inside the foreach.

1 answer

2


There must be a simpler way to do it, but this way you’ll answer:

$valores = '[1v4],,,,[5v3],,,[8v]'; //Post no seu caso
$array = explode(',',$valores); //já que não vai usar a virgula, pode explodir ela mesma.
$array = array_filter($array); //remove todos os campos vazios de um array
$array = array_values($array); //remove todos os campos vazios de um array
$array = str_replace('v',',', $array);
$remover = ['[',']'];
$array = str_replace($remover,'', $array);

foreach ($array as $a => $b) {
  $partes = explode(',',$b);
  $a = $partes[0];
  $b = $partes[1]
  echo "A: $a; B: $b\n<br>";
}

//outworking A: 1; B: 4 A: 5; B: 3 A: 8; B:

  • Thank you all, with the information provided the code worked :)

  • Magina, practice to further simplify this code ;)

Browser other questions tagged

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