What are the differences between using list() and foreach() in PHP when working with arrays?

When working with arrays in PHP, the main difference between using list() and foreach() is the way they handle array elements. list() is used to assign variables to array values based on their position, while foreach() iterates over each element in the array and allows you to access both the key and the value. Using list() can be useful when you know the exact number of elements in the array and want to assign them to individual variables. On the other hand, foreach() is more versatile and allows you to perform operations on each element of the array without needing to know its length in advance.

// Using list() to assign variables to array values
$array = [1, 2, 3];
list($a, $b, $c) = $array;
echo $a; // Output: 1
echo $b; // Output: 2
echo $c; // Output: 3

// Using foreach() to iterate over array elements
$array = [1, 2, 3];
foreach($array as $value){
  echo $value . " "; // Output: 1 2 3
}