1

I'm a PHP learner and I'm trying to get a string part from URL and echo it but only if that string contains in my array.

For example,

my dynamic URL looks like this.

test.com/?email=xyz@[email protected]

my array looks like this.

[email protected], [email protected], ...

What I want to do is echo the email only when the value is in my array. Since [email protected] is in the array, this will be echoed. But something like [email protected]will not be echoed because it is not in the array.

I tried the following but it's not working because I'm having trouble combining these two logic.

$array = array('[email protected]', '[email protected]', '[email protected]', '[email protected]');

if (isset($_GET['email'])) AND (in_array('email', $array)) {
    echo $_GET['email'];
}

which gives an error on ...

... PHP 8.0.0 - 8.0.8:

Parse error: syntax error, unexpected token "and"

... PHP 7.3.0 - 7.3.29, 7.4.0 - 7.4.21:

Parse error: syntax error, unexpected 'AND' (T_LOGICAL_AND)

3
  • 3
    in_array($_GET['email'], $array) Commented Jul 19, 2021 at 18:57
  • 3
    Maybe if (in_array($_GET['email'], $array)); Commented Jul 19, 2021 at 18:59
  • 1
    It looks like you're not seeing PHP error messages while developing, consider to use display_errors on your development machine and watch the php error log on the server. Commented Jul 19, 2021 at 19:06

1 Answer 1

2

You are on the right track. Just two small things need work:

  1. There is a syntax error in the if line. In PHP all conditions must be enclosed in a single set of parentheses. So the line should look like this

     if ( /* all conditions */ )
    
  2. The in_array() test: You want to know, if the current value of $_GET['email'] is in the array. But you test for the literal string 'email'. Change the test to look like this:

     in_array($_GET['email'], $array, true)
    

This should do the trick.

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

2 Comments

@hakre thanks for the edit! I thought the flag would not be necessary for simple string to string comparison, but with PHP’s surprising “try to make it a number first” behaviour it is indeed always better to be explicit here.
Jup, technically $_GET should contain only strings (hakre, it's the internet, someone will tell you you're wrong by saying so^^) and as the array also contains only strings it is straight forward safe to set it to true. Which is my recommendation for in_array() use anyway unless you know that you explicitly want/have mixed types in the array. And as this is example code and 2021 on stackoverflow (where mixed most likely happens in error), we should have it in all of the examples ;). Cheers!

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.