How to highlight current link in foreach loop - php

I have a script that lists all the directories as links.
<?php
$dirs = array_filter(glob('../*'), 'is_dir');
?>
<ul style="float:left;">
<?php
foreach ($dirs as $nav) {
echo "<li><a href='$nav'>".basename($nav)."</a></li>";
}
?>
</ul>
I want to highlight the current directory, or give the current link a class or id. I understand that i need if statement to accomplish this like if(currentLink=thisLink) { // add span class somehow} else {// continue looping} , but I am not completely sure how to do this.
What would be the correct way to implement this ?

Yes you are right you need if condition in your loop.
Save your current link in a variable before loop.
<?php
$dirs = array_filter(glob('../*'), 'is_dir');
?>
<ul style="float:left;">
<?php
$currentlink='abc';
foreach ($dirs as $nav) {
if($nav==$currentlink)
$class='current';
else
$class='';
echo "<li><a class='$class' href='$nav'>".basename($nav)."</a></li>";
}

Without knowing the variables to compair, syntax wise you want to do something like this
<?php
foreach ($dirs as $nav){
$class = '';
if( $currentLink == $thisLink ) {
$class = 'class="highlight"';
}
echo '<li><a href="'.$nav.'" '.$class.' >'.basename($nav).'</a></li>';
}
?>
You can look in $_SERVER to get the current url in the browser and use some of that and the basename to fill those variables in.
http://php.net/manual/en/reserved.variables.server.php

to find out the current directory name you need:
basename(getcwd())
in foreach loop use this:
if(basename($nav) == basename(getcwd()))
{
// add span class
}

First you have to get current link. Store as $current_link
<?php
$dirs = array_filter(glob('../*'), 'is_dir');
$current_dir = 'store current directory here';
?>
<ul style="float:left;">
<?php
foreach ($dirs as $nav) {
if($nav == $current_dir) {
$class_name = 'active';
}
else {
$class = '';
}
echo "<li class='$class'><a href='$nav'>".basename($nav)."</a></li>";
}
?>
</ul>
Hope it will works.

Related

Adding an incrementing prefix (html tag) and closing (html tag) suffix in a PHP foreach loop

I'm using a simple PHP foreach loop to display (in plain text) the url for each file (images in this case) found in a directory.
Here is the (working) code for that..
<?php
$directory = "imguploader/UploadFolder";
$images = glob($directory . "/*.png");
foreach($images as $image)
{
echo "http://www.myurl.com/".$image."<br />";
}
?>
Any this quite nicely almost does what I need, current results are like this..
http://www.myurl.co.uk/imguploader/UploadFolder/lp1-hot-pink.png
http://www.myurl.co.uk/imguploader/UploadFolder/lp2-green.png
http://www.myurl.co.uk/imguploader/UploadFolder/lp3-purple.png
But what I now need to do is add an (auto incrementing) html tag (as executing html, not txt)
eg <div id="img1">, <div id="img2">, <div id="img3"> etc to the start of each line, then the closing </div> tag to the end of each line the foreach creates.
Is this possible?
Try this:
<?php
$directory = "imguploader/UploadFolder";
$images = glob($directory . "/*.png");
$num = 0;
foreach($images as $image) {
$num++;
echo "<div id=\"img".$num."\">http://www.myurl.com/".$image."</div><br />";
}
?>
I've tested the above example and it works.
Use this code
<?php
$directory = "imguploader/UploadFolder";
$images = glob($directory . "/*.png");
$i = 0;
foreach($images as $image) {
$i++;
echo "<div id='img".$i."'>";
echo "http://www.myurl.com/".$image."<br />";
echo "</div>";
}
?>

Import data from xml

I'm trying to get data from an XML file using simple_xml , so far I can get all the data except the images . How can I call a single image name ?
<?php
$ur="http://services2.jupix.co.uk/api/get_properties.php?clientID=35871cc1b6d9ec6237aaaf94aa0e0836&passphrase=cvYG9f";
$xml = simplexml_load_file($ur);
foreach ($xml->property as $property):
var_dump($property->images->image);
echo 'images->image">'; // this is not displaying
endforeach;?>
My code output as the image below . How can i display image number 1
public 1 => string 'http://media2.jupix.co.uk/v3/clients/657/properties/1356/IMG_1356_9_large.jpg' (length=77)
I think SimpleXMLElement::xpath can do what you are looking for:
You can give this a try:
<?php
$ur="http://services2.jupix.co.uk/api/get_properties.php?clientID=35871cc1b6d9ec6237aaaf94aa0e0836&passphrase=cvYG9f";
$xml = simplexml_load_file($ur);
$image = $xml->xpath('//property/images/image[#modified="2014-07-23 14:22:05"]')[1]->__toString();
var_dump($image);
Or you can loop through all the images and check for the name the you are looking for:
$images = $xml->xpath('//property/images/image');
foreach ($images as $image) {
$url = $image->__toString();
if (false !== strpos($url, "_9_large.jpg")) {
var_dump($url);
}
}
If you want to get the second image of each /images section, then you could do it like this:
$images = $xml->xpath('//property/images');
foreach ($images as $image) {
if (isset($image->children()[1])) {
var_dump($image->children()[1]->__toString());
}
}
Thanks Guy I found solution to my problem .
Looking at the back at the question it seems I did not put it in a proper way
All i wanted is to display images within that section. Xpath was not necessary But i have learned from it . Here is my solution if you can improve it you are much welcome.
$url ="http://services2.jupix.co.uk/api/get_properties.php?clientID=35871cc1b6d9ec6237aaaf94aa0e0836&passphrase=cvYG9f";
$xml = simplexml_load_file($url);
foreach ($xml->property as $property):
?>
<li>
<h3> <?php echo $property->addressStreet;?> </h3>
<?php
$imgCount = count($property->images->image);
for ($i=0; $i < $imgCount; $i++) { ?>
<img src="<?php echo $property->images->image[$i];?>">
<?php } ?>
<p><?php echo limit_text($property->fullDescription,30);?></p>
<h4>£ <?php echo $property->price;?> </h4>
</li>
<?php endforeach; ?>

SimpleXml foreach : ignore element

<?php
$xml = "<articles>
<article id=\"18357302\">
<articleCategories>
<articleCategory id=\"default\"/>
<articleCategory id=\"66607\"/>
</articleCategories>
</article>
</articles>";
$feed = simplexml_load_string($xml);
$items = $feed->article;
foreach ($items as $article) {
// $categorie = $article->articleCategories->articleCategory[id];
$categories = $article->articleCategories;
print_r($categories);
echo "<br>print_r indeed returns an array, but impossible to echo it using foreach!!!<br>";
foreach ($categories->id as $category) {
if ($category != "default") {
echo $category;
}
}
}
?>
not sure what i am doing wrong, i am just trying to find a way to remove the part with the default value inside articlesCategories
<articleCategory id=\"default\"/>
The script needs to ignore this part and just use the next articleCategory from the XML file, and i would prefer to avoid removing it with regex
The script iterates over articleCategories tag.
But it needs to iterate over articleCategory tag.
The following changes will be enough.
foreach ($categories->articleCategory as $category) {
if ($category["id"] != "default") {
echo $category["id"];
}
}

Sort photos in Php gallery by date

I'm trying to build a gallery for a friend, using PHP. Currently my script imports all the images from a "gallery" folder, and it displays them alphabetically, using automatically generated thumbnails and fancybox plugin.
Is it posible to sort them by date? It doesn't matter if it's the date when they were taken or the date when they were last modified. The code I use is below. Thanks in advance!
<?php
$path = 'gallery/';
$files = scandir('gallery/');
?>
<ul>
<?php foreach ($files as $file){
if ($file == '.' || $file == '..'){
echo '';
} else {
?>
<li><a class="fancybox" rel="group" href="<?php echo $path . $file; ?>"><img src="scripts/timthumb.php?src=<?php echo $path . $file; ?>&h=194&w=224&zc=1&q=100" /></a></li>
<?php } }?>
</ul>
this php function sorts your file by the last date it was modified.
Don't forget to put in the ignored files array which files you want to be ignored.
function scan_dir($dir) {
$ignored_files = array()
$files = array();
foreach (scandir($dir) as $file) {
if (in_array($file,$ignored_files) {
$files[$file] = filemtime($dir.'/'.$file);
}
}
arsort($files);
$files = array_keys($files);
if(is_null($files))
return false;
return $files;
}
You can refactor it a bit this was made really quicly. Hope this will work

Current menu item - foreach

Consider this:
$menuItems = array (
"page1" => "1.php",
"page2" => "2.php",
"page3" => "3.php",
"page4" => "4.php",
"page5" => "5.php",
);
and now I create the menu like this:
<ul class="menu">
<?php
foreach($menuItems as $name => $url) {
echo "<li><a href='$url' class='$class'>$name</a></li>";
}
?>
</ul>
Works great. But now I need to add a class .current on the current page.
To get the current page I do this:
<?php
function curPageName() {
return substr($_SERVER["SCRIPT_NAME"],strrpos($_SERVER["SCRIPT_NAME"],"/")+1);
}
$curpage = curPageName();
?>
And it also works great.
SO I guess the question is how do I assign $curpage to the ... current page? :)
Thank you.
Alex
<ul class="menu">
<?php
foreach($menuItems as $name => $url) {
if ($url === $curpage){
$class.=' .current';
}
echo "<li><a href='$url' class='$class'>$name</a></li>";
}
?>
</ul>
Easy, inside your loop, check if $url == $curpage, and append appropriately.
Example:
<?php
$menuItems = array(
"page1" => "1.php",
"page2" => "2.php",
"page3" => "3.php",
"page4" => "4.php",
"page5" => "5.php",
);
$current_item = "2.php"; //Assume we got this from the function
?>
<ul class="menu">
<?php
foreach ($menuItems as $name => $url) {
echo "<li><a href='$url'";
if ($url == $current_item) {
echo " class='current'";
}
echo ">$name</a></li>\n";
}
?>
</ul>
<ul class="menu">
<?php
foreach($menuItems as $name => $url) {
$class = 'default';
if (curPageName() == $name) {
$class.='.current';
}
echo "<li><a href='$url' class='$class'>$name</a></li>";
}
?>
</ul>
So I made it work with your help! Thanks guys.
Special thanks for Adel - although you had a mistake there I fixed it like this:
foreach($menuItems as $name => $url) {
$class = 'default';
if (curPageName() == $url) {
$class.=' \. current';
}
echo "<li><a href='$url' class='$class'>$name</a></li>";
}
Awesome! Thanks again!
<?php
$menuItems = array(
'page1' => '1.php',
'page2' => '2.php',
'page3' => '3.php',
'page4' => '4.php',
'page5' => '5.php',
);
$current_page = curPageName();
?>
<ul class="menu">
<?php
foreach ($menuItems as $name => $url) {
?>
<li><a href="<?php=$url?>"
<?php
if ($url == $current_page) {
?>
class="current"
<?php
}
?>
><?php=$name?></a></li>
<?php
}
?>
</ul>
Why use the curPageName () at each iteration?
You can use a ternary syntax to solve your problem. It consists in this syntax:
(if condition ? true : false)
So we can use this way on your answer comparing the curPageName with the url inside the foreach loop.
$url == curPageName() ? 'current' : 'notCurrent'
Now you just need to use this in your favor.
I like the syntax of printf. So the code is more clean. Try this:
<?php
/**
* curPageName() is defined in question
* my_links() is a shortcut to array defined in question
*/
$template = "<li%s>%s</li>";
$links = my_links();
$current = curPageName();
print '<ul class="menu">';
foreach ($likns as $name => $url) {
$class = $current == $url ? ' class="current"' : '';
printf($template, $class, $url, $name);
}
print '</ul>';
Each %s item in $template will be changed by sequential variable. So, if you need to change the template the code is clean and easyest to give a maintance.
Or, if you want another easiest template way, use the php template syntax. Note the use of : after the foreach statement and the use of endforeach. You can see that I am using the short code of echo <?=$var?> that is more compreensible than <?php echo $var ?>.
<?php
/**
* curPageName() is defined in question
* my_links() is a shortcut to array defined in question
*/
$links = my_links();
$current = curPageName();
?>
<ul class="menu">
<?php foreach ($links as $name => $url): ?>
<li<?=($current == $url ? ' class="current"' : '')?>>
<?=$name?>
</li>
<?php endforeach ?>
</ul>

Categories