Jump to content

Archived

This topic is now archived and is closed to further replies.

AdRock

How to get a function to work [RESOLVED]

Recommended Posts

I have got a function to shorten the length of a string so it if is more than 40 characters it has .... at the end

I am having problems calling the function to display the string.  it displays nothing.

This is the first time i've used a function so i don't know if i've done it right

[code]function DisplayURL() {
    if (strlen($url) > 40) {   
         $url = substr($url,0,40);
         echo $url ."..."; }
    else {
         echo $url;
    }
}

//show data matching query:
echo "<table border='0' id='MyTable' class='style3' cellpadding='3'>\n";
echo "<tr bgcolor='#CDE1FF'><th>Name</th><th>Location</th><th>URL</th></tr>\n";

for($i = 0; $i < $numofrows; $i++) {

    $row = mysql_fetch_array($q); //get a row from our result set

    $url = $row['url'];

    if($i % 2) { //this means if there is a remainder
        echo "<tr bgcolor='#FFFFCC'>\n";
    } else { //if there isn't a remainder we will do the else
        echo "<tr bgcolor='#FFFFFF'>\n";
    }
    echo "<td width='30%'>".$row['name']."</td><td width='30%'>".$row['location']."</td><td width='40%'><a href='".$row['url']."' target='_blank'>".DisplayURL()."</a></td>\n";
    echo "</tr>\n";
}[/code]

Share this post


Link to post
Share on other sites
[code]function DisplayURL() {
    global $url;
    if (strlen($url) > 40) { 
        $url = substr($url,0,40);
        echo $url ."..."; }
    else {
        echo $url;
    }
}[/code]
you need ot either make $url a global or use it like this..

[code]function DisplayURL($url) {
    if (strlen($url) > 40) { 
        $url = substr($url,0,40);
        echo $url ."..."; }
    else {
        echo $url;
    }
}[/code]

    echo "<td width='30%'>".$row['name']."</td><td width='30%'>".$row['location']."</td><td width='40%'><a href='".$row['url']."' target='_blank'>".DisplayURL($url)."</a></td>\n";



regards
Liam

Share this post


Link to post
Share on other sites
Thanks Liam...that worked

Another problem now....the urls are displayed outside of the table before the first row.
How do i get them to go back into the right table row as an hyperlink.....it's lost the anchor tags

Is it becuase the function echoes the $url and in the line that calls the function the whole line is being echoed to there's an echo within an echo>

Share this post


Link to post
Share on other sites
You should return the string from the function instead of echoing it:
[code]<?php
function DisplayURL($url) {
    if (strlen($url) > 40) return(substr($url,0,40) . '...');
    else return($url);
}?>[/code]

Ken

Share this post


Link to post
Share on other sites

×

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.