0

I've searched long and hard for an answer to doing this & have come up with nothing. I know someone here will have an answer.

First, I get the URL and grab the subsite out of the beginning:

<?php
// get page URL
    $pageURL = 'http';
    if ($_SERVER["HTTPS"] == "on") {$pageURL .= "s";}
    $pageURL .= "://";
    if ($_SERVER["SERVER_PORT"] != "80") {
        $pageURL .= $_SERVER["SERVER_NAME"].":".$_SERVER["SERVER_PORT"].$_SERVER["REQUEST_URI"];
    } else {
        $pageURL .= $_SERVER["SERVER_NAME"].$_SERVER["REQUEST_URI"];
    }
// get host name from URL
    $url = preg_replace('(https?://)', '', $pageURL);
    $affUrl = explode('.', $url);
    $aff = $affUrl[0];
?>

If the URL is affiliate1.domain.com, this returns affiliate1 as $aff.

Next, I have affiliates.txt each with a different name on each line:

affiliate1
affiliate2
affiliate-3 (yes, this is correct)

Then, I read that file into an array:

<?php
// read affiliates.txt and create array
    $affs = file("affiliates.txt"); 

// search for affiliate in array
    $inarray = array_search($aff, $affs); // i've tried in_array() also
    if ($inarray !== false) echo '<img src="affiliatelogos/$aff.jpg" class="aff-img" alt="$aff" />';
?>

However, even when I hardcode an affiliate name into array_search():

    $inarray = array_search('affiliate1', $affs);

It returns nothing. What am I doing wrong here?

2 Answers 2

3

Each line includes a newline character, you can ignore them by providing a flag to the "file" function:

$affs = file('affiliates.txt', FILE_IGNORE_NEW_LINES);
Sign up to request clarification or add additional context in comments.

2 Comments

Ah, even better than my solution of trimming all the values. I didn't know of that option, thanks for pointing it out.
WOO! That did it. WONDERFUL!
0

Try trimming all the values in the array to remove trailing whitespace and new line characters. This is the simplest way of doing it:

array_walk($affs, create_function('&$val', '$val = trim($val);')); 

Comments

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.