Home » Php » php – How to use foreach loop for this array

php – How to use foreach loop for this array

Posted by: admin February 25, 2020 Leave a comment

Questions:
<?php

$dataPoints = array(array("y"=> 26274, "label"=> "2007"),array("y"=> 26380, "label"=> "2008"),array("y"=> 25058, "label"=> "2009"),array("y"=> 24864, "label"=> "2010"),array("y"=> 26707, "label"=> "2011"),array("y"=> 29309, "label"=> "2012"),array("y"=> 34519, "label"=> "2013"),array("y"=> 40101, "label"=> "2014"),array("y"=> 48401, "label"=> "2015"),array("y"=> 58580, "label"=> "2016")
);

?>

I have this code, how to use foreach loop for this so only digit and year changes accordingly

How to&Answers:
<?php 
$dataPoints = array(array("y"=> 26274, "label"=> "2007"),array("y"=> 26380, "label"=> "2008"),array("y"=> 25058, "label"=> "2009"),array("y"=> 24864, "label"=> "2010"),array("y"=> 26707, "label"=> "2011"),array("y"=> 29309, "label"=> "2012"),array("y"=> 34519, "label"=> "2013"),array("y"=> 40101, "label"=> "2014"),array("y"=> 48401, "label"=> "2015"),array("y"=> 58580, "label"=> "2016")
);

foreach($dataPoints as $key=>$value){
 echo $value['y'];
 echo "-------";
 echo $value['label'];
 echo "<br>";
}
?>

Answer:

The example below iterates over the array $dataPoints and saves a copy of the single element in $dataArray. Within the foreach loop you can access the copy and echo it:

foreach( $dataPoints as $dataArray ) {
  echo "y: " . $dataArray['y'] . "<br>";
  echo "label: " . $dataArray['label'] . "<br>";
}

This example outputs:

y: 26274
label: 2007
y: 26380
label: 2008
// and so on...

If you would like to edit the single elements, this would be helpful for you.
This code iterates over the array $dataArray too but it saves a reference (read more about references) of the single element in $dataArray (& sign). You can access it within the foreach loop and change the original array – not only the copy:

foreach( $dataPoints as &$dataArray ) {
  $dataArray['y'] = 'whatever';
}