Insert static code block into a php "while loop" after "N" loops. - php

I have a php while loop, but I want to insert a "static" code block into it after the third item in the loop and then continue the loop after the static content. Can someone help me update my code to accomplish the "desired outcome" below?
My Code
$x = 0;
while($x <= 5) {
$contentItems = $relatedArray[$rand_keys[$x]];
$contentItems = explode('|', $contentItems);
echo '
<p><img class="faux" src="'.$contentItems[4].'"></p>
';
$x++;
}
Desired Outcome
Loop Content
Loop Content
Loop Content
**STATIC CONTENT**
Loop Content
Loop Content
Loop Content

Just add an if conditional inside of your while loop that checks against the index:
$x = 0;
while($x <= 5) {
// Will only trigger halfway through the loop
if ($x == 3) {
echo '**STATIC CONTENT**';
}
$contentItems = $relatedArray[$rand_keys[$x]];
$contentItems = explode('|', $contentItems);
echo '<p><img class="faux" src="'.$contentItems[4].'"></p>';
$x++;
}
Note that this will still output the original item at this position. If you want to replace it instead, you'll want to wrap everything related to $contentItems inside of an else conditional :)

Related

Php count elements inside loop not outside

I know how to count elements inside a loop, but tried and can´t find a solution. Actually, I can count the elements in loop in this way:
$i = 0;
foreach ($Contents as $item)
{
$i++;
}
echo $i;
But in my case, I have large function and I can do this, but need more time for count elements inside. I can´t put the string for showing number elements inside loop outside of the function. I must show inside loop all number of elements and show as this. Here's an example:
$i = 0;
foreach ($Contents as $item)
{
print "Number Elements it´s : $i";
print "Element ".$i."<br>";
$i++;
}
The problem here is that the phrase "number elements it´s" always repeats, because inside loop, and all time $i show me 0,1,2,3,4,5 ...... and all time the same as number of elements inside loop.
My idea and question is if it´s possible inside loop to show the number of elements and after this show the elements as this structure when executing the script:
Númber elements it´s : 12
Element 1
Element 2
Element 3
.
.
.
.......
This it´s my question. I hope you understand it all. Thanks in advance.
As mentioned in the comments, youu will need to use the count() function for that. If you insist on having it inside the loop, simply do it like this:
$i = 0;
foreach ($Contents as $item)
{
if($i == 0) {
print "Number of Elements is : " . count($Contents) . "<br><br>";
}
print "Element ".$i."<br>";
$i++;
}

How to get the value of a $total before the code calculated?

I want to show a content of variable whom been calculate in a foreach loop. The problem is that I want to echo it before the loop.
<?php
echo $total; // note this line I want to appear the total count of loop. the problem is it cannot appear because it is in the above of foreach loop. I want to appear it in this above before foreach loop.
$total = 0;
foreach($pathList as $item) {
$fileInfo = pathinfo($item);
if(preg_match(strtolower('/\b'.$_POST['song'].'\b/'), strtolower($filename))) {
$total = $total + 1; // the total count of foreach loop I want to appear in echo $total
}
// some code
}
?>
I do want to echo it inside the loop but only once after completed the loop.
Any idea how do I solve this problem? I tried global $total but not working...
Thanks in advance!
Generally - NO. You cannot echo variable that not been calculate yet (synchronization in PHP).
If all you do in the for-loop regarding $total is increasing by 1 then you actually count the number of element in the array so you can just do:
echo count($pathList);
Before the for-loop. Documentation in here
Updated:
If $total is affected in the loop (as you updated the question) then I believe best practice will be to counting array element first (without executing any more code), then echo the $total, afterward, loop on the original data and execute the rest of your code.
$total = 0;
foreach($pathList as $item) {
$fileInfo = pathinfo($item);
if(preg_match(strtolower('/\b'.$_POST['song'].'\b/'), strtolower($filename))) // or what ever condition you have to check for total
$total = $total + 1;
}
echo count($total); // give you the count you need
foreach($pathList as $item) {
// exec the rest of your code
}
This may run at O(2*n) but its not worse
It is not possible. Lines are executed in the order in which they appear in the script.
The value of $total at the end of the loop is equal to the value of count($pathList)
If you need the value of the last iterated element of the $pathList before the execution of the loop, then it can be echoed as
echo $pathList[count($pathList)-1];

How to pas array in loop in php?

I am facing the problem is that I want to display all image by using array and loop,it is not showing all image ,it does show only one image.Here is my code
if($objResult['Image_Type'] == '01') {
$img11 = array($objResult['Image_Name']);
for ($i=0; $i < count($img11[$i]); $i++) {
$im_mouths = array($img11[$i]);
}
}
here is in the database to extract out all image
the out put is showing only one image by using this code
<? echo $im_mouths[0].'11111'.'<br>';?>
<? echo $im_mouths[1].'222222'.'<br>';?>
<? echo $im_mouths[2].'333333'.'<br>';?>
I am not sure I'm doing correctly or not ,help me out this problem.
Thanks :)
It's only showing one image because you're re-writing $im_mouths each time you loop. You should change your loop to do the following:
$im_mouths = array();
if($objResult['Image_Type'] == '01') {
$img11 = array($objResult['Image_Name']);
for ($i=0; $i < count($img11[$i]); $i++) {
$im_mouths[] = array($img11[$i]);
}
}
We initialize $im_mouths as an array, then add each element to the array as an element: $im_mouths[] = ....
You need to simplify your code a bit.
Assuming you have a outer loop for retrieving data from database:
$im_mouths = array();
while ($objResult = $res->fetch()) {
if($objResult['Image_Type'] == '01') {
$im_mouths[] = $objResult['Image_Name'];
}
}
Now you have $im_mouths array of elements of image names, as many as you have in database. So as you see you don't need unnecessary inner for loop
Finally to see what you have in your $im_mouths array, you can print_r it:
print_r($im_mouths);
In your example, the variable $im_mouths should contain only the last image ( that is, 20140923jaobangsaen01.png ). Because you are using simple variable to store the image, so that the variable may contain last image while the program flow comes out from the for loop. So that the output of your example is correct. If you want to show each images means, you should use array variable to store all the images and display back to the required place. Rearrange the code like following,
$im_mouths = array();
if($objResult['Image_Type'] == '01') {
$img11 = array($objResult['Image_Name']);
for ($i=0; $i < count($img11[$i]); $i++) {
$im_mouths[] = array($img11[$i]);
}
}
Hope it will work fine for you.
Use can use foreach to display the images instead of using echo for each image.
$num = 1111; //if required
foreach ( $im_mouths as $value ) {
echo $value.$num;
$num += 1111;
}

php set a menu from an array for loop display

$array=array('menu1','menu2','menu3','menu4','menu5','menu6','menu7','menu8','menu9','menu10');
I storied some menu names into an array, Then output some like
in diffirent page, the menu always show 5 items and current page is always 2nd.
And if the current page is in this case, it will loop display menu1, menu2, menu3 after menu10.
foreach($array as $k=>$r){
if($r==$current){
$n=$k;//count current memu position
}
}
echo '<ul>';
foreach($d as $k=>$r){
if($n>1&&$n<7){//normal situation like first image
if($k==($n-1)){
echo '<li><a>'.$r.'</a></li>';
}else if($k==$n){
echo '<li class="current">'.$r.'</li>';
}else{
echo '<li><a>'.$r.'</a></li>';
}
}else{
//How to do in the case of the second image?
}
}
echo '</ul>';
I think you would also like the menu look like this when the current selection is menu1:
menu10
menu1 [selected]
menu2
menu3
menu4
Here is the algorithm. It looks confusing but I am sure you can figure it out.
$array=array('menu1','menu2','menu3','menu4','menu5','menu6',
'menu7','menu8','menu9','menu10');
$current = 'menu1';
$startIndex = array_search($current, $array)-1;
$total = count($array);
$result = array();
for($index = $startIndex ; $index <$startIndex+5; $index++){
$result[] = $array[($index+$total)%$total]; //using % operator
}
print_r($result);
Try this:
if($k==($n-1)){
echo '<li><a>'.$r.'</a></li>';
}else if($k==$n){
echo '<li class="current">'.$r.'</li>';
}else{
if($k >= count($d)-1)
echo ''<li><a>'.$d[$k-count($d)+1].'</a></li>';
else
echo ''<li><a>'.$r.'</a></li>';
}
This actually should work for both cases, so you can remove the big if statement and put this as the body of your foreach.

Constructing Multidimensional Tree From Array

I am trying to create a tree from an array like this:
array('admin/home', 'admin/home/page', 'admin/test', 'team/tree/template', 'site');
Or more visually seen as:
admin/home
admin/home/page
admin/test
team/tree/template
site
However, I also need the last nested string of each array to become bolded to signify that it is a webpage itself.
The final product should look like:
admin
home
page
test
team
tree
template
site
I have used a few different solutions from this site but I have not been able to get the right outcome.
Any ideas or examples on where I should start would be greatly appreciated, thanks.
You are probably looking for something like this:
<?php
$items = array('admin/home', 'admin/home/page', 'admin/test', 'site', 'team/tree/template');
sort($items);
$previous = array();
foreach ($items as $item) {
$path = explode('/', $item);
// $i is common nesting level of the previous item
// e.g. 0 is nothing in common, 1 is one level in common, etc.
for ($i = 0; $i < min(count($path), count($previous)) && ($path[$i] == $previous[$i]); $i++) { }
// close <ul> from previous nesting levels:
// that is, we close the amount of levels that the previous and this one have NOT in common
for ($k = 0; $k < count($previous)-$i-1; $k++) { echo "</ul>"; }
// $j is the current nesting level
// we start at the common nesting level
for ($j = $i; $j < count($path); $j++) {
// open <ul> for new nesting levels:
// i.e., we open a level for every level deeper than the previous level
if ($j >= count($previous))
echo "<ul>";
echo "<li>";
// make the path bold if the end of the current path is reached
if (count($path)-1 == $j)
echo "<b>" . $path[$j] . "</b>";
else
echo $path[$j];
echo "</li>";
}
$previous = $path;
}
// close remaining <ul>
for ($k = 0; $k < count($previous); $k++) { echo "</ul>"; }
?>
Note that I order the array to make sure that all nested items come next to each other.
It might have some bugs, but I guess you can work them out yourself. Note that I close the list items before opening a nested <ul>. This is not really how it should; I guess you actually should open the nested <ul> in the final <li> at that level, but you can figure that out yourself.
Update I updated the code to properly close the <ul>'s in some cases.

Categories