Page 1 of 1
php arrays and for loop
Posted: Tue Jan 29, 2008 2:45 am
by nileshkulkarni
hi all consider folowing array.
$names[0] = "maya1";
$names[1] = "maya2";
$names[2] = "maya3";
$names[3] = "maya4";
$names[4] = "maya5";
i want to create output using for loop. and it should look like
name[0]=maya1
name[0]=maya2 .......
i wrote for loop like below but it is not working
$i=0;
$counter=4
for ($i=0; $i<=$counter; $i++)
{
echo 'names ['.$i.'] = '.$names[$i].' <br>';
}
i just see name[0] but not the value assigned to it. where i am making mistake?
pl advice.
nilesh
Re: php arrays and for loop
Posted: Tue Jan 29, 2008 3:29 am
by nileshkulkarni
sorry for my mistake in last php code. actual array is like this
$counter = 1;
$names['$counter'] = 'maya1'; $counter++;
$names['$counter'] = 'maya2'; $counter++;
$names['$counter'] = 'maya3'; $counter++;
$names['$counter'] = 'maya4'; $counter++;
$names['$counter'] = 'maya5';
for ($i=1; $i<=5; $i++)
{
echo 'names ['.$i.'] = '.$names[$i].' <br>';
}
outout of this is just names[1], names[2],..... it is not printing maya1 maya 2.......
nilesh
Re: php arrays and for loop
Posted: Tue Jan 29, 2008 3:49 am
by Ollie Saunders
I started replying to you first post. Your 2nd one makes a lot more sense. You are defining an element in the array called '$counter' not called 1.
I don't even need to define $counter to do this because the variable isn't being referenced:
Code: Select all
$counter = 534; // irrelevant, this variable will never be used
$names=['$counter'] = 4;
echo $names['$counter'];
Consider
- Removing the quotes around $counter so the variable is actually referenced.
- Assigning to arrays without a counting variable
Code: Select all
$names = array('foo', 'bar', 'zim', 'gir');
Use print_r() and var_dump() to view the contents of arrays.
Re: php arrays and for loop
Posted: Tue Jan 29, 2008 5:32 am
by nileshkulkarni
i will try out and will revert back if needed.
thanks.
nilesh
Re: php arrays and for loop
Posted: Tue Feb 05, 2008 2:54 am
by nileshkulkarni
pl find the situation where u have 2 use variable in array itself. i hvae database in which name,date of birth and email is stored. i check today's date and if someone is having b'day then send email to them. i do not know how many people have b'day today. so i need to have $i as inisde $bname[]. I tested this code and found that it is working
nilesh
-----------
while ($i < $num)
{
$bname[$i]=mysql_result($result,$i,"firstname");
$bemail[$i]=mysql_result($result,$i,"email");
$i++;
}
Re: php arrays and for loop
Posted: Tue Feb 05, 2008 3:08 am
by Christopher
For the second you probably want:
Code: Select all
for ($i=1; $i<=5; $i++)
{
$names[$i] = 'maya' . $i; // or "maya$i"
}
For the second you probably want:
Code: Select all
while ($i < $num)
{
$bname[$i]=mysql_result($result,$i,"firstname");
$bemail[$i]=mysql_result($result,$i,"email");
$i++;
}