Tell me more ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

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?

share|improve this question

2 Answers

up vote 3 down vote accepted

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);
share|improve this answer
Ah, even better than my solution of trimming all the values. I didn't know of that option, thanks for pointing it out. – EdoDodo Aug 6 '11 at 18:41
WOO! That did it. WONDERFUL! – joshmax Aug 6 '11 at 18:44

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);')); 
share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.