Repeat var with dynamic value PHP - php

I've a certain amount of posts, each post contains a modal (sort of a popup) the HTML of this modal is in the $html[] var. The code below works well except as you can see it is not dynamic.
What i've tried:
$post_count = [1,2,3,4,5,6,7,8,9,10,11,12]; // i've to mannualy add a number according to the number of posts
$counter = 1;
foreach($number_of_modals as $modal){
echo $html[$counter];
$counter++;
}
Explanation of what i need to accomplish
$post_count; // if this val is 3 for example
echo $html[1];
echo $html[2];
echo $html[3];

As Paul suggested, use either a for loop, or a while loop:
$post_count = 3;
$counter = 0;
while ($counter <= $post_count) {
echo $html[$counter];
$counter++;
}

Can you try this one?
foreach($number_of_modals as $key => $modal){
echo $html[$key];
}
Since you haven't given the structure of $number_of_modals array, I assumed it's like the $html array
$modal = array('1', 'abc', 'etc');
Which translates to $modal = array(0 => '1', 1 => 'abc', 2 => 'etc');
In that foreach each $key corresponds to 0,1,2 which gives the $counter you are looking for.

Related

Targeting last child in PHP array within foreach

I am trying to target the last child of an array (within a foreach statement) to enable me to slightly adjust the output of just this item. I have tried numerous approaches but not having any breakthroughs. My loop is very simple:
// Loop through the items
foreach( $array as $item ):
echo $item;
endforeach;
The above works fine, but I want to change the output of the final item in the array to something like:
// Change final item
echo $item . 'last item';
Is this possible?
$last_key = end(array_keys($array));
foreach ($array as $key => $item) {
if ($key == $last_key) {
// last item
echo $item . 'last item';
}
}
Use count(), this will count all elements of your array. Use the length of the count for your last element index. as below. Set the last element as "Last Item" before your start your foreach this way you wont need no validation.
$array[count($array) - 1] = $array[count($array) - 1]."Last item";
foreach( $array as $item ){
echo $item;
}
It sounds like you want something like this:
<?php
// PHP program to get first and
// last iteration
// Declare an array and initialize it
$myarray = array( 1, 2, 3, 4, 5, 6 );
// Declare a counter variable and
// initialize it with 0
$counter = 0;
// Loop starts from here
foreach ($myarray as $item) {
if( $counter == count( $myarray ) - 1) {
// Print the array content
print( $item );
print(": Last iteration");
}
$counter = $counter + 1;
}
?>
Result Here
You can use end
end : Set the internal pointer of an array to its last element
$fruits = array('apple', 'banana', 'cranberry');
echo end($fruits); // cranberry
Hey you can simply use end function for the last element. You don't need to iterate it.
Syntax : end($array)

PHP replace every 2nd

<?php
$fact_BB = array("[start]", "[mid]", "[end]");
$fact_HTML = array("<tr><td class='FactsTableTDOne'><p>", "</p></td><td class='FactsTableTDTwo'><p>", "</p></td></tr>");
$str_Facts = str_replace($fact_BB, $fact_HTML, $row['facts']);
echo $str_Facts;
?>
Is it possible to switch between 2 $fact_HTML?
1. $fact_HTMLone = "code";
2. $fact_HTMLtwo = "code";
3. $fact_HTMLone = "code";
4. $fact_HTMLtwo = "code";
5. $fact_HTMLone = "code";
etc. etc.
Sure. With $fact_HTML[0], $fact_HTML[1], $fact_HTML[n] etc. you can access your $fact_HTML array. Using modulo of 2 you can always access every 2nd (or first and second) elements of the array.
To check if the element is even or odd you can use:
if ($n % 2 == 0) {
//even element
} else {
//odd element
}
Also you can use Modulo 2 ($n % 2) as n to iterate through the array in the same way. You can also combine both variants.
$count = 10; //number of facts
for ($n = 0; $n < $count; $n++) {
$fact_HTML[$n % 2] = $fact;
}
What you want to achieve is a replace of some strings. I'd suggest a solution like this:
<?php
$str_Facts = $row['facts'];
$replacements = array( "[start]" => "<tr><td class='FactsTableTDOne'><p>",
"[mid]" => "</p></td><td class='FactsTableTDTwo'><p>",
"[end]" => "</p></td></tr>" );
foreach ($replacements as $repkey => $repval) {
$str_Facts = str_replace($repkey,$repval,$str_Facts);
}
echo $str_Facts;
?>
If you want to go on with your approach, you'd loop through the arrays (you have to ensure that the both arrays have the same number of elements).
<?php
$str_Facts = $row['facts'];
for ($i=0;$i<count($fact_BB);$i++) {
//if you want to switch every uneven, do this:
if ($i%2!=0) continue;
$str_Facts = str_replace($fact_BB[$i],$fact_HTML[$i],$str_Facts);
}
echo $str_Facts;
?>

php array insert and print

This is a part of my PHP program.
//for example: $rec_count = 30
$totalpages=(int)$rec_count/10;
$index=0;
$pageslink[$totalpages]='';
while($index <= $totalpages ){
$pageslink['index']=$index;
echo '<br>Index: '.$index.'<br>';
echo '<br>Page '.$pageslink['index'].' ';
$index++;
}
print_r($pageslink);
It comes out like this:
Index: 0
Page 0
Index: 1
Page 1
Index: 2
Page 2
Index: 3
Page 3 Array ( [3] => [index] => 3 )
Its supposed to be pageslink[0] = 1; pageslink[1 ]= 2; pageslink[3] = 3; But When I print_r() the pageslink array , only 3 as a value. I've been trying to find out why only 3 is inserted as value in array.
I am a beginner, so thank you in advance for your help. It will be much appreciated.
In the short version of this answer, arrays in PHP start counting from 0, not 1. So on the first loop it would be 0 and the second loop it would be 1 and so on.
You're using
$pageslink['index'] = $index;
Meaning you set the item with the named key 'index' in your array to the value of your variable $index, instead of using $index as your key.
In PHP (and many other languages) you can refer to an item in an array with its index number (0, 1, 2, etc.) or by a word (named key).
For example:
$myArray = ['John', 'London'];
echo $myArray[0]; // John
echo $myAray[1]; // London
or
$myArray = ['name' => 'John', 'city' => 'london'];
echo $myArray['name']; // John
echo $myArray['city']; // London
What you are doing now is setting the same item in your array (the item you're calling index) to a new value every loop, overwriting its old value. So after all the loops you'll only have the last value saved.
You want something like this:
$pageslink[$index] = $index + 1;
Which will translate to:
$pageslink[0] = 1; // first loop
$pageslink[1] = 2; // second loop
$pageslink[2] = 3; // third loop
By the way, a for loop would be cleaner in your example code:
$rec_count = 30
$totalpages=(int)$rec_count/10;
$pageslink = array(); // this is how to create an array, not with ''
for($i=0;i<$totalpages;$i++){
$pageslink[] = $i;
}
print_r($pageslink);
You over complicate the code here, try:
$totalpages=(int)$rec_count/10;
$index=0;
$pageslink = array();
while($index <= $totalpages ){
$pageslink[]=$index+1;
echo '<br>Index: '.$index.'<br>';
echo '<br>Page '.$pageslink[$index].' ';
$index++;
}
print_r($pageslink);
But this code is very weird. You just create array of n elements.
Could you explain what do you try to achieve here?

how to skip elements in foreach loop

I want to skip some records in a foreach loop.
For example, there are 68 records in the loop. How can I skip 20 records and start from record #21?
Five solutions come to mind:
Double addressing via array_keys
The problem with for loops is that the keys may be strings or not continues numbers therefore you must use "double addressing" (or "table lookup", call it whatever you want) and access the array via an array of it's keys.
// Initialize 25 items
$array = range( 1, 25, 1);
// You need to get array keys because it may be associative array
// Or it it will contain keys 0,1,2,5,6...
// If you have indexes staring from zero and continuous (eg. from db->fetch_all)
// you can just omit this
$keys = array_keys($array);
for( $i = 21; $i < 25; $i++){
echo $array[ $keys[ $i]] . "\n";
// echo $array[$i] . "\n"; // with continuous numeric keys
}
Skipping records with foreach
I don't believe that this is a good way to do this (except the case that you have LARGE arrays and slicing it or generating array of keys would use large amount of memory, which 68 is definitively not), but maybe it'll work: :)
$i = 0;
foreach( $array as $key => $item){
if( $i++ < 21){
continue;
}
echo $item . "\n";
}
Using array slice to get sub part or array
Just get piece of array and use it in normal foreach loop.
$sub = array_slice( $array, 21, null, true);
foreach( $sub as $key => $item){
echo $item . "\n";
}
Using next()
If you could set up internal array pointer to 21 (let's say in previous foreach loop with break inside, $array[21] doesn't work, I've checked :P) you could do this (won't work if data in array === false):
while( ($row = next( $array)) !== false){
echo $row;
}
btw: I like hakre's answer most.
Using ArrayIterator
Probably studying documentation is the best comment for this one.
// Initialize array iterator
$obj = new ArrayIterator( $array);
$obj->seek(21); // Set to right position
while( $obj->valid()){ // Whether we do have valid offset right now
echo $obj->current() . "\n";
$obj->next(); // Switch to next object
}
$i = 0;
foreach ($query)
{
if ($i++ < 20) continue;
/* php code to execute if record 21+ */
}
if want to skipped some index then make an array with skipped index and check by in_array function inside the foreach loop if match then it will be skip.
Example:
//you have an array like that
$data = array(
'1' => 'Hello world',
'2' => 'Hello world2',
'3' => 'Hello world3',
'4' => 'Hello world4',
'5' => 'Hello world5',// you want to skip this
'6' => 'Hello world6',// you want to skip this
'7' => 'Hello world7',
'8' => 'Hello world8',
'9' => 'Hello world8',
'10' => 'Hello world8',//you want to skip this
);
//Ok Now wi make an array which contain the index wich have to skipped
$skipped = array('5', '6', '10');
foreach($data as $key => $value){
if(in_array($key, $skipped)){
continue;
}
//do your stuf
}
You have not told what "records" actually is, so as I don't know, I assume there is a RecordIterator available (if not, it is likely that there is some other fitting iterator available):
$recordsIterator = new RecordIterator($records);
$limited = new LimitIterator($recordsIterator, 20);
foreach($limited as $record)
{
...
}
The answer here is to use foreach with a LimitIterator.
See as well: How to start a foreach loop at a specific index in PHP
I'm not sure why you would be using a foreach for this goal, and without your code it's hard to say whether this is the best approach. But, assuming there is a good reason to use it, here's the smallest version I can think of off the top of my head:
$count = 0;
foreach( $someArray as $index => $value ){
if( $count++ < 20 ){
continue;
}
// rest of foreach loop goes here
}
The continue causes the foreach to skip back to the beginning and move on to the next element in the array. It's extremely useful for disregarding parts of an array which you don't want to be processed in a foreach loop.
for($i = 20; $i <= 68; $i++){
//do stuff
}
This is better than a foreach loop because it only loops over the elements you want.
Ask if you have any questions
array.forEach(function(element,index){
if(index >= 21){
//Do Something
}
});
Element would be the current value of index.
Index increases with each turn through the loop.
IE 0,1,2,3,4,5;
array[index];

How to tell a foreach loop only to go through the loop for x times?

how can I achieve this correctly:
$array[]['title'] = $secondarray["title"];
$array[]['content'] = $secondarray["content"];
foreach($array as $arr) {
$output.="<div>".$arr['title']."</div><br/>";
}
unset($arr);
Now for example the $array[]['title'] contains 10 entries and $array[]['content'] also 10.
But the foreach loop will give 20 div as result since the $array contains 10+10 elements. How can I tell the foreach to take only the amount of elements in $array[]['title'] (since $array[]['content'] is the content that belongs to each title)? So that means go only 10 times through the loop.
PS: Please no answer that I should use "for".
Thanks for your help,
phpheini
Another method would be to only feed it a partial array:
foreach (array_slice($array, 0, 10) as $row)
{
...
i suggest putting title and content into a single array, then you can use foreach without counting and title with its content is 'grouped':
$array[] = array ( 'title' => $secondarray['title'], 'content' => $secondarray['content'] );
foreach($array as $arr) {
echo '<h1>',htmlspecialchars($arr['title']),'</h1>';
echo '<p>',htmlspecialchars($arr['content']),'</p>';
}
Use something like this, but you should really use LIMIT if data comes from database.
$i = 0;
foreach($array as $arr) {
$i++;
$output.="<div>".$arr['title']."</div><br/>";
if ($i == 10) break;
}
maybe
$array[] = array(
'title' => $secondarray["title"],
'content' => $secondarray["content"],
);
after it will be no need to limit loop times

Categories