Read Array out of foreach

Asked

Viewed 1,016 times

2

In this script below I read an array inside the foreach, more how can I read it out? when I give an echo it only returns me 1 id

 $data = unserialize ($linha["range_ids"]); 
 // a:3:{i:1052;s:4:"1052";i:1053;s:4:"1053";i:1054;s:4:"1054";}

 foreach($data as $key => $value): //Ler a Variavel 
  echo      $range = $key.',';  // Retorno do echo 1052,1053,1054, 
 endforeach; 

 echo $range; // Retorno do echo 1054   (Preciso que retorne assim 1052,1053,1054)
  • 1

    I think the loop is not necessary in this case. See my answer how you can do with implode

3 answers

2

To do this use the function print_r.

example:

$meu_array = array(1, 2, 3);

print_r($_POST);

print_r($meu_array); // Array (3) { 1, 2, 3 }

You can also use the function implode

echo implode(',', array(1, 2, 3)); // Imprime 1, 2, 3
  • Hello friend sorry I didn’t explain right I changed it in the script. My array is returning via unserialize when I law inside the foreach coming 1052,1053,1054 until then this correct just can’t pass this result out.

1

The variable $range this having the value overwritten each time the foreach runs.

What you seem to need is to add to the existing value, something like this:

$range = "";

foreach($data as $key => $value):
  echo      $range = $range + $key.',';  
 endforeach; 

 echo $range;
  • Hello friend sorry I didn’t explain right I changed it in the script. My array is returning via unserialize when I law inside the foreach coming 1052,1053,1054 until then this correct just can’t pass this result out

  • I do not know if it will work very well to mix sum with concatenation. I will test this here on the command line

  • I forgot it was PHP and you don’t use '+' for concatenation, it should be a dot there

  • 1

    Still works, @Diogo. PHP is crazy anyway

1


Simple, it uses an easier way to perform the foreach in the array.

$lista = array('1052','1053','1054');
$a = "";
foreach($lista as $b){
 $a .= $b . ',';
}
echo $a; // Resultado: 1052,1053,1054

See the PHP Guide: Array

  • gave error Warning: Invalid argument supplied for foreach() in

  • 2

    Error in your foreach. It should be foreach($lista as $b)

Browser other questions tagged

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