If I have an array with 4 values:
Code: Select all
$array = array( 'one', 'two', 'three', 'four' );
I can loop through it in a few different ways, I could count how many values it has using the count() function, then use a for or while loop, but both are rather inconvenient, foreach is designed to make life easier. A foreach loop allows us to easily read the indexes as well as values within the array.
for loop:
Code: Select all
$totalPositions = count($array); // 4
for( $i = 0; $i < $totalPositions; $i++ ) // as long as $i is less than 4, loop and increment $i
{
echo $array[$i] . '<br />';
}
The result would be:
Code: Select all
one<br />two<br />three<br />four<br />
We can achieve the exact same result with a foreach loop using a lot less code:
Code: Select all
foreach( $array as $value )
{
echo $value . '<br />';
}
With a foreach loop we can also read the indexes/keys of the positions within the array
Code: Select all
foreach( $array as $key => $value )
{
echo $key . ' => ' . $value . '<br />' . "\n";
}
Code: Select all
0 => one<br />
1 => two<br />
2 => three<br />
3 => four<br />
Code: Select all
$array = array( 'green' => 'oranges', 'red' => 'bananas', 'blue' => 'tomatoes' );
foreach( $array as $key => $value )
{
echo $key . ' => ' . $value . '<br />' . "\n";
}
Code: Select all
green => oranges<br />
red => bananas<br />
blue => tomatoes<br />
The differences between preg and str_replace aren't very big, they both simply find matches in a string and replace them, preg_replace simply has a lot more functionality when it comes to matching.
Fighting for peace is declaring war on war. If you want peace be peaceful.