1

I am trying to use the following code to check if the current URL is within an array.

$reactfulPages = array(
    'url-one',
    'url-two',
    'url-three',
);

if (strpos($url, $reactfulPages) == true) {
    echo "URL is inside list";
}

I think the way I have set up the array is incorrect as the following code (checking for one URL) works fine..

if (strpos($url,'url-one') == true) { // Check if URL contains "landing-page"

}

Can anyone help me out?

2
  • ... What? The code is working and it's not suppose to or what? Commented Mar 21, 2016 at 11:16
  • @James reactfulPages is a array so you can't use "strpos($url, $reactfulPages)".str pos use for finding a word or character in a string rather than in array. For finding a url is exist in array you can use method in_array($value,$array) Commented Mar 21, 2016 at 11:24

2 Answers 2

7

The array is fine, the functions to check is not the right way. The strpos() function is for checking the string position(s).

The right way to check if something is in your array you can use the in_array() function.

<?php
$reactfulPages = array(
    'url-one',
    'url-two',
    'url-three',
);

if(in_array($url, $reactfulPages)) {
    echo "The URL is in the array!";
    // Continue
}else{
    echo "The URL doesn't exists in the array.";
}
?>

I hope this will work for you.

Sign up to request clarification or add additional context in comments.

Comments

2

The function strpos() looks for a substring within a string, and returns the the position of the substring if it is found. That is why your last example works.

If you want to check whether something exists in an array, you should use the in_array() function, like so:

$reactfulPages = array(
    'url-one',
    'url-two',
    'url-three',
);

if (in_array($url, $reactfulPages) == true) {
    echo "URL is inside list";
}

However, since you're comparing URL's, I'm assuming you want to check whether the URL contains one of the strings from the array, not necessarily matching them as a whole. In this case, you will need to write your own function, which could look like this:

function contains_any($string, $substrings) {
    foreach ($substrings as $match) {
        if (strpos($string, $match) >= 0) {
            // A match has been found, return true
            return true;
        }
    }

    // No match has been found, return false
    return false;
}

You can then apply this function to your example:

$reactfulPages = array(
    'url-one',
    'url-two',
    'url-three',
);

if (contains_any($url, $reactfulPages)) {
    echo "URL is inside list";
}

Hope this helps.

Comments

Your Answer

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