0

Before I start, I should let you know that I'm hardly experienced in PHP. In fact, I pretty much only started using it last week, so I'm using it as if it were JavaScript or something.

Anyway, I'm trying to streamline the dynamic serving of content, via PHP, on my website as much as best as I can and as I know how.

So, I do this by:

  1. Creating an array of every URL variable that I'm currently using.
  2. Querying IDPage(), which includes a FOR loop that cycles through the array, compares the index place to the current URL variable and returns the index place, if matched.
  3. Using the returned string to decide which content to include.

 

Pre-<!DOCTYPE>

<?php
    $root = $_SERVER["DOCUMENT_ROOT"];
    $array_IDs = array("404", "home", "item2", "item3", "item4");
    global $root, $array_IDs;
?>

<head>

<?php
    function IDPage(){
        for ($i = 0; $i < count($array_IDs); $i++){
            if (isset($_GET[$array_IDs[$i]])){
                return $array_IDs[$i];
            }
        }
    }
?>

<body>

<article>
    <?php 
        $response = IDPage();

        if ($response == "404"){
            include($root . "/path/file.ext");
        }

        if ($response == "home"){
            include($root . "/path/file.ext");
        }

        if ($response == "item2"){
            include($root . "/path/file.ext");
        }

        if ($response == "item3"){
            include($root . "/path/file.ext");
        }

        if ($response == "item4"){
            include($root . "/path/file.ext");
        }
    ?>
</article>

Using the current set up, the array always returns 0 and, with a little more digging, this seems to be because count() thinks that $array_IDs has no values. Yet, this works if you place the FOR loop in the same block as <body>s (and mod the code to work from the same block, of course).

Again, I know it's crude but it's only a small site, I don't know any better and I don't think I'm ready to get into databases and all that yet. If anyone's got any better ideas, though, feel free to let me know, so long as I'm capable. :L

1 Answer 1

1

Use global keyword inside your function to import that variable in your function:

function IDPage(){
    global $array_IDs;
    for ($i = 0; $i < count($array_IDs); $i++){
        if (isset($_GET[$array_IDs[$i]])){
            return $array_IDs[$i];
        }
    }
 }
Sign up to request clarification or add additional context in comments.

1 Comment

Oh, I see. That didn't occur to me, because, as I said, I'm using it as if it were JavaScript. That's great, thanks @Blaster. :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.