Reputation: 3223
For instance, i have a 2 list of values that has no relevance with each elements. I'm planning to put this values manually.
$a1 = 'red';
$a2 = '007';
$a3 = 'gun';
$a4 = 'apple';
$b1 = 'poison';
$b2 = 'movie';
$b3 = 'man';
$b4 = 'store';
echo $a.' with '.$b
I want an output like:
red with poison
007 with movie
gun with man
apple with store
So I want $an
displayed with $bn
. I have thought of using a for loop, but I don't know how to do it (I'm really new to PHP...)
Any suggestions? any help would be great. thanks in advance!
Upvotes: 2
Views: 662
Reputation: 545
change your setup to an array
$a[1] = 'red';
$a[2] = '007';
$a[3] = 'gun';
$a[4] = 'apple';
$b[1] = 'poison';
$b[2] = 'movie';
$b[3] = 'man';
$b[4] = 'store';
then use a for loop
for($n=0;$n<sizeof($a);$n++){
echo $a[$n] . ' with ' . $b[$n];
}
with this method you can call any part of the variable with its known number at any time elsewhere in the script, such as:
echo $b[2];
This is an explanation on the for loop.
for() This calls the loop and is limited by
{and
}
The arguments in the loop start with your starter.
In my case I used $n. I set $n to 0 to give the loops somewhere to start from.
The next part of the loop is how many times you want it iterated in comparison to your start variable. This is usually dependent on the size of an array but can also be a number. The argument I created here to determine the iterations. sizeof() is another function within php to get the number of elements within an array or variable (or i think it can do file sizes too). I am telling it to make sure that as long as $n is less than the size of the variable to keep looping. You normally want a loop to end after a while else pages take forever to load.
Finally you add the thing at the end to increase the counter so to speak. This can be anything once again but using $n++ means it increases the value of $n by 1 each time until the end of the loop
Upvotes: 1
Reputation: 11425
I think the simplest is to use a associative array and foreach
like this:
foreach (array("red" => "poison",
"007" => "movie",
"gun" => "man",
"apple" => "store") as $a => $b) {
echo "$a with $b\n";
}
Upvotes: 1
Reputation: 615
Use arrays :
$a[0] = 'red';
$a[1] = '007';
$a[2] = 'gun';
$a[3] = 'apple';
$b[0] = 'poison';
$b[1] = 'movie';
$b[2] = 'man';
$b[3] = 'store';
foreach($a as $key=>$value)
{
echo $value.' with '.$b[$key];
}
Upvotes: 3
Reputation:
for (var $i = 1; $i <= 4; $i++) {
echo ${"a".$i} . " with " . ${"b".$i};
}
see http://php.net/manual/en/language.variables.variable.php
Upvotes: 0
Reputation: 53525
You can use arrays:
//that's how you add elements to an array
$a[] = 'red';
$a[] = '007';
$a[] = 'gun';
$a[] = 'apple';
$b[] = 'poison';
$b[] = 'movie';
$b[] = 'man';
$b[] = 'store';
//and this is how you read from an array
for($i=0; $i<count($a); $i++){
echo $a[$i].' with '.$b[$i] . "\n";
}
Upvotes: 0