Skip to content
Advertisement

PHP return list as a function result

I am an absolute beginner in PHP. I have a file main.php where I have a call to a php function:

JavaScript

I have a file navigation.php which is required in main.php, it has a small constructor to build the right structure of the navigation, it looks like this:

JavaScript

This works completely fine for me, but I want to have some options, that’s why I establish a function:

JavaScript

What is the right way for me to return this HTML structure that I generate by calling the navigation function?

Advertisement

Answer

To keep your code clean, you should seperate the template (html) from the business logic (php). Therefore your approach is great. Here ‘s a short example, how you could solve your issue.

First think about all the data you want to use in your function. As far as we can see, you need the pages and the options. Both arguments are arrays.

JavaScript

As you can see, the function does nothing more, as you have defined already. It takes another array parameter, where the pages are stored in. At the end of the function it includes the navigation template. There ‘s nothing more to do in PHP side.

The template navigation.phtml should look something like you already have.

JavaScript

I ‘ve shortened the code example. To keep the logic in your template as small as possible you could filter the exluded pages before in your function to avoid the in_array if condition in your template.

In your main.php file, you can simple call the navigate function.

JavaScript

The $pages and $options variables have to be declared before the call of the navigation function.

User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement