Include single lines of php in ordered list - php

I am fairly new to php and not sure if it is possible to include php file content line by line.
Say I have an ordered list and a php file with three lines. I can include the whole content using
<?php include 'myfile.php' ?>
my question is, if it is possible to include single lines.
myfile.php
apples
bananas
oranges
index.php
<ol>
<li>???????</li>
<li>???????</li>
<li>???????</li>
</ol>
Thanks

There are more possibilities one of them is to put your content in a text file and load the content with file for example. Then you can iterate through every line with foreach.
The other way is to put your values in an array if your don't need it in a file.
$fruits = array(
'apples',
'bananas',
'oranges'
);
Then you can iterate with foreach over that array.
http://php.net/manual/en/language.types.array.php
Before you start you should read about that things and perhaps you start at the beginning of that documentation.

You can read in the file as an array:
$myFile = file('myfile.php', FILE_IGNORE_NEW_LINES); // FILE_IGNORE_NEW_LINES strips the new line characters from the array
now you can either print a single line:
echo $myFile[2]; // echo the third item
or output everything as a HTML list:
echo '<ol>';
foreach ($myFile as item) {
echo '<li>'. $item .'</li>';
}
echo '</ol>';

You can do in various ways:
declaring variables for each one:
myfile.php
<?php
$apples = "apples";
$bananas = "bananas";
$oranges = "oranges";
and print them in the list:
index.php
<ol>
<li><?php echo $apples; ?></li>
<li><?php echo $bananas; ?></li>
<li><?php echo $oranges; ?></li>
</ol>
OR declaring one array with all of them.
myfile.php
<?php
$fruits = array( 'apples', 'bananas', 'oranges' );
and print them in the list using a foreach:
index.php
<ol>
<?php
foreach ($fruits as $fruit){
echo '<li>'.$fruit.'</li>';
}
?>
</ol>
Good Luck!

Related

Getting the value outside the foreach php loop

Here is the code used to get the ids of a images in a gallery
<?php $images = get_field('photogallery');?>
<?php foreach( $images as $image ): ?>
<?php echo $image['ID']; ?>
<?php echo ','; ?>
<?php endforeach; ?>
I get the output
1102 , 3380 , 3348 , 3354 , 3355 ,
I would like to get this outside the loop because the result must be used in other shortcode also I see there is a whitespace after every number.
the result must be
1102,3380,3348,3354,3355
Please help me.. thanks
You don't need to put <?php ... ?> everytime everywhere for each statement. Keep in mind that each time you close with ?> all characters are sent to the client until the next opening <?php, that's why you obtain spaces around each comma:
<?php foreach( $images as $image ): ?>#
#####<?php echo $image['ID']; ?>#
#####<?php echo ','; ?>#
<?php endforeach; ?>
(I changed white-spaces to #, this way you can see characters sent to the client (the browser)).
You can use array_map to "filter" only ID items and implode to join them , then you only need to store the result in a variable ($result here).
<?php
$images = get_field('photogallery');
$result = implode(',', array_map(function ($i) { return $i['ID']; }, $images));
echo $result;
?>
Now you can use $result later everywhere you want.
Much simpler:
<?php echo implode(',' array_column($images, 'ID')); ?>
extract the ID values using array_column()
implode() those array values using a comma

Foreach - show the number of items

I have this code to count the objects in the foreach loop (images in a gallery):
<?php $images = get_field('galerie'); if( $images ): ?>
<?php $i=1; foreach( $images as $image ): ?>
<?php echo $i++; ?>
<?php endforeach; ?>
<?php endif; ?>
So when i have 4 items (images) it gives me
1 2 3 4
But i need only the highest number like:
4
when i have 4 imgages. Any idea how do i get this number?
Why not just count the images ?
<?php
$images = get_field('galerie');
if($images && is_array($images)) { // in case get_galerie returns null or empty strings when no images...
echo count($images);
}
?>
Also, no need to put <?php ... ?> tags on each line.
Enclose a whole block of PHP code into this tag, it's far more readable, and works the same.
There is a count function.
$length = count($images);
it's simple, just do it like this:
<?php $images = get_field('galerie'); if( $images ): ?>
<?php $i=0; foreach( $images as $image ): ?> //$i=0 not 1
<?php $i++; ?>
<?php endforeach; ?>
<?php echo $i; ?>
<?php endif; ?>
L.E: just for those who down-voted my answer, I kept the users way of coding for 2 (I thought obvious) reasons:
He might actually need the foreach()
He might be new to PHP, and if the iterator method ($i = 1; $i++) is what he knows he should stick with it until he discovers something new. This is a algorithm method inherited from C, Pascal and other much "older" programming languages.
Of course, the count() method is faster and gives a way less pain in the behind, but this is NOT a bad way to code for a beginer.
Hope this helps! :D

Using Data attributes With Data from an array

I am using data-attributes in my portal page to describe favorite links. This is very easy to do it you are using a regular list ( because you can individually put the custom "data-special" in.
However when you have lots of links in an array and you are using foreach how do you pick out and apply a data-special to individual links within the array? ? the way I see it its either all or none within the foreach.
data-special is my own declaration. I apply a Unicode character through CSS to the links that are special.
Thank you for reading and your time.
$portal = array(
"Twitter" => "http://twitter.com",
//another 20 array elements
);
ksort($portal);
foreach ($portal as $key => $item):
echo("<li><a rel=\"external\" href=\"$item\">$key</a></li>");
?>
<?php endforeach; ?>
I need to add data-special to specific links but am unsure of how to pick them out as they are in an array
EDIT
This is what I am trying to achieve on perhaps 5 of some links in the array
<li data-special>Kular</li>
Without knowing any more, try something like this (filling in the blanks where required). I'm assuming you're using the UTF-8 content type
<?php foreach ($portal as $key => $item) :
$special = /* boolean statement; is $key or $item special */
? 'data-special="true"' : '';
?>
<li <?php echo $special ?>>
<a rel="external"
href="<?php echo htmlspecialchars($item, ENT_QUOTES, 'UTF-8') ?>">
<?php echo htmlspecialchars($key, ENT_QUOTES, 'UTF-8') ?>
</a>
</li>
<?php endforeach ?>
A more concrete example might be if you wanted to set only the Twitter key to special..
$special = $key == 'Twitter'
? 'data-special="true"' : '';
Perhaps a better example might be...
// before the foreach loop
$specials = array('Twitter', 'Google', 'Facebook');
then, in your loop
$special = in_array($key, $specials)
? 'data-special="true"' : '';

object foreach loop iterate only even values

Basically I have a set of object values I want render in 2 separate html lists
I figure the simplest way to do this is by displaying evens only in one list, and odd only in the other
Here is the current code for displaying a single list
<ul>
<?php foreach ($values as $value) : ?>
<li><?php echo $value->value; ?></li>
<?php endforeach; ?>
</ul>
Try this:
<ul>
<?php
/* read the index key */
foreach ($values as $key => $value) :
/* skip the current element if it doesn't have an even index */
if($key % 2 == 1) continue;
?>
<li><?php echo $value->value; ?></li>
<?php endforeach; ?>
You didn't specify if the array has integer index. So I use a separate index pivot. This will do.
$v=array();
$index = 1;
foreach ($values as $value){
$v[($index++)%2][]=$value->value;
}
list ($evens, $odds) = $v;
echo "<ul><li>".implode("</li><li>", $odds)."</li></ul>"; // show list of odds
echo "<ul><li>".implode("</li><li>", $evens)."</li></ul>"; // shows list of even

How to get last key with values from array of arrays? PHP

This is what i am currently using
<?php $sidebar = $this->data['sidebar'];
$lastKey = array_pop(array_keys($sidebar));
$sidebar = $this->data['sidebar'][$lastKey]; ?>
<?php foreach($sidebar as $key => $item) { ?>
<li id="<?php echo Sanitizer::escapeId( "pt-$key" ) ?>"<?php
if ($item['active']) { ?> class="active"<?php } ?>><?php echo htmlspecialchars($item['text']) ?></li>
<?php } ?>
This is what i get (http://pastebin.com/t6Y2ZtMF) when i print_r($sidebar);
I want to get the last Array which is Categories and turn it into links.
I am new to php, so my method could be wrong even though it works. I is there a right way to pull the Categories Array or the above code is good as it is?
$lastValue = end($array);
$lastKey = key($array); // current key, which is the last since you called end()
After update:
You don't seem to be needing the key, only the array:
<?php $lastSidebarValue = end($this->data['sidebar']); ?>
<?php foreach ($lastSidebarValue as $key => $item) : ?>
business as usual...
<?php endforeach; ?>
Since you know you want the key 'Categories' though (not the last key), this seems the most logical thing to do:
<?php foreach ($this->data['sidebar']['Categories'] as $key => $item) : ?>
business as usual...
<?php endforeach; ?>
I think the end() function would be a great solution: http://php.net/manual/en/function.end.php
It basically returns the value of the last element in the array being passed to it.
$sidebar = end($sidebar);
If you want to get a key/value pair without popping & pushing the array, set the internal cursor to the end of the array and then use list and each to get the key & value.
// set up your array however you had it
$array = ...;
// move the cursor to the end of the array
end($array);
// use list() and each() to extract your key/value pair
list($key,$val) = each($array);
// $key will now have the last key
// $val will have the last value
perhaps, end:
$fruits = array('apple', 'banana', 'cranberry');
echo end($fruits); // cranberry
You can use `end()` instead of `array_pop()`. But both works for the **last element** of the array. The only difference is `end()` **points out** the **last element** of the array without effecting it and `array_pop()` **pops** the element off the **end** of array.
Please go through the following links for detail information
end() | array_pop()

Categories