I want to access the values of an associative array in PHP. I populate the array using the following loop in PHP:
$db = array("a","b","c");
foreach ($db as $q) {
$$q = 'value';
}
This version prints the correct values
foreach ($db as $q) {
echo '<li>'; echo $$q; echo '</li>';
}
\\THIS GIVES ME THE CORRECT OUTPUT <li>value</li><li>value</li><li>value</li>
But I want to access the values through their index
$num = count($db);
for ($i = 0; $i < $num; $i++) {
echo '<li>'; echo $$db[$i]; echo '</li>';
}
\\\\THIS GIVES ME THE WRONG OUTPUT (EMPTY STRINGS <li></li><li></li><li></li>
What is going wrong in the second version? How can I access the values in this associative array through an index correctly?
echo '<li>'; echo $$db[$i]; echo '</li>';
In this line is one $ too much. Write:
echo '<li>'; echo $db[$i]; echo '</li>';
This should do the trick.
PS: You don't have to write echo everytime. Use string concatenation:
echo '<li>' . $db[$i] . '</li>';
You are trying to do something quite strange, anyway the solution to your problem are braces: { }
$num = count($db);
for ($i = 0; $i < $num; $i++) {
echo '<li>'; echo ${$db[$i]}; echo '</li>';
}
Look how braces are resolving the ambiguity, since without them, php wouldn't know if you were referring to ${$db}[$i] or ${$db[$i]}
Related
I have a foreach statement in my app that echos a list of my database results:
<?php
foreach($featured_projects as $fp) {
echo '<div class="result">';
echo $fp['project_name'];
echo '</div>';
}
?>
I would like to:
On every third result, give the div a different class. How can I achieve this?
You can use a counter and the modulo/modulus operator as per below:
<?php
// control variable
$counter = 0;
foreach($featured_projects as $fp) {
// reset the variable
$class = '';
// on every third result, set the variable value
if(++$counter % 3 === 0) {
$class = ' third';
}
// your code with the variable that holds the desirable CSS class name
echo '<div class="result' . $class . '">';
echo $fp['project_name'];
echo '</div>';
}
?>
<?php
foreach ($featured_projects as $i => $fp) {
echo '<div class="result' . ($i % 3 === 0 ? ' third' : '') . '">';
echo $fp['project_name'];
echo '</div>';
}
?>
If the $featured_projects array is based on incremental index you could simply use the index and the modulo % operator.
Otherwise you would have to add a counter.
http://php.net/manual/en/language.operators.arithmetic.php
add a counter in this loop and check if counter equals three and apply class.
Using a counter and modulo operator this is easy to implement
<?php
foreach($featured_projects as $fp) {
if(++$i % 3 === 0) {
$class = ' something';
} else {
$class = '';
}
echo '<div class="result' . $class . '">';
echo $fp['project_name'];
echo '</div>';
}
?>
<?php
$i = 0;
foreach($featured_projects as $fp) {
echo '<div class="'.($i++%3 ? 'result' : 'other_class').'">';
echo $fp['project_name'];
echo '</div>';
}
?>
What leaves your code mostly in tact would be
<?php
$i = 1;
foreach($featured_projects as $fp) {
printf ('<div class="%s">',(($i % 3) ? "result" : "result_every_third" ));
echo $fp['project_name'];
echo '</div>';
$i++;
}
?>
But you may want to consider using a for or while construct around "each($featured_projects)" (see http://php.net/manual/en/function.each.php) which may result in neater code.
<?php
$counter = 0;
foreach ($featured_projects as $fp) {
echo '<div class="result' . ($counter++ % 3 === 0 ? ' third' : '') . '">';
echo $fp['project_name'];
echo '</div>';
}
?>
You can add a counter in loop ...try the following...
<?php
$i = 0;
foreach($featured_projects as $fp) {
$i = ++$i;
if(($i%3) == 0)
{
$class1 = 'test1';
}
else
{
$class1 = 'test2';
}
echo '<div class="'.$class1.'">';
echo $fp['project_name'];
echo '</div>';
}
?>
This is the working version, sorry for my prev version:
<?php
$featured_projects[0]['project_name'] = "pippo";
$featured_projects[1]['project_name'] = "pippo2";
$featured_projects[2]['project_name'] = "pippo3";
$class[0] = "class1";
$class[1] = "class2";
$i=0;
foreach($featured_projects as $fp) {
$i++;
if ($i == 3) {
$c = $class[1];
$i=0;
} else {
$c = $class[0];
}
echo "<div class=\"$c\">";
echo $fp['project_name'];
echo "</div>\n";
}
?>
Produces:
<div class="class1">pippo</div>
<div class="class1">pippo2</div>
<div class="class2">pippo3</div>
I have very weird issue with php foreach loop in IE 11. In FF, Chrome, Opera, Safari, IE 7 8 9 10 Foreach loop works fine.
I used for() loop for dummy text it works fine in IE 11. But i don't know how to call arrays in for or while loop
here is my code.
$img_num4 = 4;
$data_chunks = array_chunk($wp_images, $num_img);
echo '<ul id="id1">';
foreach ($data_chunks as $data_chunk) {
echo '<li class="id2">';
foreach($data_chunk as $data) {
if($data['image_links_to'])
echo '<a href="'.$data['image_links_to'].'" '.$new_window.'>';
echo '<img src="'.$data['file_url'].'" class="logo-img" alt="" />';
if($data['image_links_to'])
echo '</a>';
}
echo '</li>';
}
echo '</ul>';
I don't know why foreach loop not working in IE 11 only. Any Suggestions.
I also try this:
$img_num4 = 4;
$data_chunks = array_chunk($wp_images, $num_img);
echo '<ul id="id1">';
for($i=1; $i<=10; $i++){
echo '<li>'.$i.'</li>';
}
/*foreach ($data_chunks as $data_chunk) {
echo '<li class="slide">';
foreach($data_chunk as $data) {
if($data['image_links_to'])
echo '<a href="'.$data['image_links_to'].'" '.$new_window.'>';
echo '<img src="'.$data['file_url'].'" class="logo-img" alt="" />';
if($data['image_links_to'])
echo '</a>';
}
echo '</li>';
}*/
echo '</ul>';
It shows me correct data in IE 11. But foreach loop not work
please tell me how can i call arrays in for or while loop
With a for loop it should be like :
$img_num4 = 4;
$data_chunks = array_chunk($wp_images, $num_img);
echo '<ul id="id1">';
$len = $data_chunks.lenght;
for ($i = 0; $i < $len; $i++) {
$data_chunk = $data_chunks[$i];
echo '<li class="id2">';
$len2 = $data_chunk.lenght;
for ($j = 0; $j < $len2; $j++) {
$data = $data_chunk[$j];
if($data['image_links_to']) {
echo '<a href="'.$data['image_links_to'].'" '.$new_window.'>';
}
echo '<img src="'.$data['file_url'].'" class="logo-img" alt="" />';
if($data['image_links_to']) {
echo '</a>';
}
}
echo '</li>';
}
echo '</ul>';
a while loop is not so useful here.
As metionned in comments, php's an html preprocessor so it does not need any browser to work. Maybe you should look on the html source in your IE11 browser to see what is buggy.
MAYBE (and that's an important part of the sentence) IE11 doesn't display <li> if it does not contains any text. Here you only put an <img> (sometimes with a link).
You should try replacing img tag with text in your foreach loop.
Apolo
how can i increment my css ID using php programmatically?
foreach ($query_cat->result() as $row_cat)
{
$row_cat_id = $row_cat->id;
echo '<div class="product-wrapper">';
echo '<div id="product-header" class="product-header">';
echo $row_cat->title;
echo '</div>';
echo '</div>';
$query_prod = $this->db->get_where('products', array('category_id'=>$row_cat_id));
foreach ($query_prod->result() as $row_prod)
{
$row_prod_id = $row_prod->id;
echo '<div id="product-contents" class="product-contents">';
echo $row_prod->title.' '.$row_prod->id;
echo '</div>';
}
}
what i want to happen is to increment the id product-header and product-contents depending on the numbers of rows generated
something like this
product-header1, product-header2, product-header3....
product-contents1, product-contents2, product-contents3....
thanks!
Just initialise an incremental variable before the foreach.
$i = $j = 0;
foreach ($query_cat->result() as $row_cat) {
$i++;
$row_cat_id = $row_cat->id;
echo '<div class="product-wrapper">';
echo '<div id="product-header'.$i.'" class="product-header">';
...
foreach ($query_prod->result() as $row_prod) {
$j++;
$row_prod_id = $row_prod->id;
echo '<div id="product-contents'.$j.'" class="product-contents">';
...
}
}
$i = $j = 1;
foreach (...) {
printf('<div id="product-header-%u" class="product-header">', $i++);
foreach (...) {
printf('<div id="product-contents-%u" class="product-contents">', $j++);
}
}
I have an array containing a "Variable" amount of results/entries.
I use foreach as normal to echo the array results.
Problem: I want to wrap every 5 results from the array in Unordered list.
I do not know the total number of results since it's variable. So for example if it contains 18 items. It should display 4 ULs, the first 3 ULs containing 5 results and the last UL contains only the remaining 3 items.
Is that simple to do? Thanks very much in advance for your help. :)
I rarely used this function, but array_chunk seems to do what you want.
$chunks = array_chunk($original, 5);
foreach ($chunks as $each_chunk) {
// echo out as unordered list
}
This is a fairly straightforward algorithm:
$htmlOutput = "";
for($i=0;$i<count($myArray);$i++)
{
if($i%5==0)
{
$htmlOutput.= "<ul>";
}
$htmlOutput.= "<li>".$myArray[$i]."</li>";
if($i%5==4)
{
$htmlOutput.= "</ul>";
}
}
if(count($myArray)%5!=0)
{
$htmlOutput.= "</ul>";
}
echo $htmlOutput;
You may need to modify this a bit to suit your requirements
$cnt = 1;
foreach ($arr as $key => $val)
{
if($cnt==1) echo "<ul>";
echo "<li>$val</li>";
$cnt++;
if($cnt==5)
{
echo "</ul>";
$cnt=1;
}
}
How about this:
<?php
$num_per_list = 5; // change me
$dudes = array("bill","jim","steve","bob","jason","brian","dave","joe","jeff","scott");
$count = 0;
$list_items = "";
foreach($dudes as $dude) {
$break = (($count%$num_per_list) == ($num_per_list-1));
$list_items .= "<li>" . $dude . "</li>";
if(($break) || (count($dudes)==($count+1))) {
$output = "<ul>" . $list_items . "</ul>";
$list_items = "";
// Output html
echo $output;
}
$count++;
}
?>
Let's suppose you put the list in an array...
$count = 0;
foreach ($unorderedList as $item) {
$count = ($count + 1)%5;
if ($count == 0) {
// wrap here
}
...do the stuff for every item you need
}
Hi i am trying to use simple_html_dom for a text(website) clustering project but i have run into a weird problem. When i use echo inside the outer loop the url and the snippet are what you would expect but when i try to echo the array contents i have gathered outside the loop the urls are ok but the snippets are gone and the last snippet is in their place.
<?php
// create HTML DOM
include("simple_html_dom.php");
$search_query = 'something';
$j = 1;
$k = 1;
/*************************GOOGLE***************************/
for ($i = 0; $i < 1; $i++) {
$url = sprintf('http://www.google.com/search?q=%s&start=%d', $search_query, 10 * $i);
$html = file_get_html($url);
foreach ($html->find('a[class=l]') as $element) {
$urls[$j] = $element->href;
echo $element->href . "\n\n\n\n\n";
$j++;
}
foreach ($html->find('div[class=s]') as $element) {
$snippets[$k] = $element->innertext;
echo $element->innertext . "\n\n\n\n\n";
$k++;
}
}
$j = 1;
foreach ($snippets as $elemement) {
echo $urls[$j] . "\n" . $element . "\n\n\n\n";
$j++;
}
?>
Are you sure you did not made a typo in your code?
foreach ($snippets as $elemement) {
echo $urls[$j] . "\n" . $element . "\n\n\n\n";
$j++;
}
element and elemement are different; Your loop executes fine but your statement probably doesn't.
You made a typo, $elemenent really should be $element.
foreach ($snippets as $element) {
echo $urls[$j] . "\n" . $element . "\n\n\n\n";
$j++;
}
This is one reason to get used to make readable code. It's not because others like it, but because it makes debugging much easier.