Reputation: 3
Can someone please help me fix this code up? I am getting some weird error: this for loop not working properly
<?php
$languages=array('te','hi');
for($langIndex=0;$langIndex<count($languages);$langIndex++)
{
echo $languages;}
?>
expected result:
te,hi
actual result:
Array Array
Upvotes: 0
Views: 70
Reputation: 509
and for performacne reason!
<?php
$languages=array('te','hi');
for($langIndex = 0, $count = count($languages) ;$langIndex < $count; $langIndex++)
{
echo $languages[$langIndex];
}
?>
Upvotes: 0
Reputation: 9616
If you want just the desired result te,hi
from that array, use
echo implode(',', $languages);
Upvotes: 0
Reputation: 3308
You call your array ($languages) every time, in your loop...
try with :
for($langIndex=0;$langIndex<count($languages);$langIndex++)
echo languages[$langIndex];
}
or
foreach($languages as $langue){
echo $langue;
}
Upvotes: 0
Reputation: 670
You accidentally use echo array
. Try this:
<?php
$languages=array('te','hi');
for($langIndex=0;$langIndex<count($languages);$langIndex++)
{
echo $languages[$langIndex];
}
?>
Upvotes: 0
Reputation: 1054
You should use array index when addressing to elements of array
<?php
$languages=array('te','hi');
for($langIndex=0;$langIndex<count($languages);$langIndex++)
{
echo $languages[$langIndex];
}
?>
Upvotes: 0
Reputation:
You're trying to print out the whole $languages
array each time around the loop -- there's nothing inside the loop which actually looks at what value $langIndex
has. You could either print out the string at the index you're currently looking at:
echo $languages[$langIndex];
Or you could save yourself some trouble and use a foreach
loop instead:
foreach ($languages as $lang) {
echo $lang;
}
Upvotes: 0
Reputation: 51797
you have to get the array-entry for the iteration first ($languages[$langIndex]
):
for($langIndex=0;$langIndex<count($languages);$langIndex++) {
$language = $languages[$langIndex];
echo $language;
}
another possibility would be to use a foreach-loop:
foreach($languages as $langIndex => $language) {
echo $language;
}
Upvotes: 2