Joshua Olds
Joshua Olds

Reputation: 177

Foreach loop inside function with sets of two variables

This is a basic example of something I am trying to figure out so I can understand how to apply the same concept to other functions...

My question is for example I have a function that will create a series of links that would look something like this:

function link($link, $title){
    echo '<li><a href="'.$link.'">'.$title.'"></li>';
}

And call it like this:

link('page1.html', 'Title 1', 'page2.html', 'Title 2);

Obviously, output should be

<li><a href="page1.html">Title 1</a></li>
<li><a href="page2.html">Title 2</a></li>

I am sure a foreach is involved here but again I am here asking the question so guess I don't really have a clue. I know that I could just call link() twice or multiple times but as mentioned I want to apply this to other functions, this is just a basic example that I could think of. Thanks in advance!

Upvotes: 1

Views: 31

Answers (1)

Marcos Dimitrio
Marcos Dimitrio

Reputation: 6852

You need to use func_get_args():

function getlinks(){
    $arguments = func_get_args();
    $count = count($arguments);
    for($i = 0; $i < $count; $i+=2) {
        echo '<li><a href="'.$arguments[$i].'">'.$arguments[$i+1].'</a></li>';
    }
}

getlinks('page1.html', 'Title 1', 'page2.html', 'Title 2');

That's a pretty basic example, you should do your checking, e.g. did you receive an even number of arguments? In this case, it could look like this:

    if ($count % 2 != 0) {
        $msg = "Expecting pairs of link/title, received an odd number of arguments.";
        throw new Exception(__METHOD__ . ': ' . $msg);
    }

Upvotes: 2

Related Questions