Home PHP variable shortcut?
Reply: 3

PHP variable shortcut?

Jonathan Safa
1#
Jonathan Safa Published in 2017-09-14 02:42:54Z

Is there a shorter way to say this? In my header, I have this:

$white1 = '/~jonathan/www/index.php';
$white2 = '/';
echo ($_SERVER['REQUEST_URI']); 

And here is how I am processing it:

<?php 
if (
(($_SERVER['REQUEST_URI']) == $white1) 
or 
(($_SERVER['REQUEST_URI']) == $white2)
) 
echo 'custom-class'; 
?>

I'd also like it to have a $white3 and $white4 that allow for ?lang=en

Matthew Poer
2#
Matthew Poer Reply to 2017-09-14 02:55:44Z

When there are a handful of options I want to match against, I like to use in_array like this,

$options = array(
  '/',
  '/~jonathan/www/index.php',
);
if(in_array($_SERVER['REQUEST_URI'], $options)) {
  echo 'custom-class'
}

This method makes it easy to add to the list of $options without changing the payload or adding anything more than a single entry as needed. I like to keep the array sorted to make entries easy to find and keep it clean.

antoni
3#
antoni Reply to 2017-09-14 03:12:05Z

You can do this using in_array:

if (in_array($_SERVER['REQUEST_URI'], [$white1, $white2])) echo 'custom-class';

Of course you can define your array of matches before.

WhatsYourIdea
4#
WhatsYourIdea Reply to 2017-09-14 02:49:06Z

Put all variables in an array and check if $_SERVER['REQUEST_URI'] is in the array.

<?php

$w = ['/~jonathan/www/index.php', '/'];
echo ($_SERVER['REQUEST_URI']);

if (in_array($_SERVER['REQUEST_URI'], $w))
    echo 'custom-class';

?>
You need to login account before you can post.

About| Privacy statement| Terms of Service| Advertising| Contact us| Help| Sitemap|
Processed in 0.348482 second(s) , Gzip On .

© 2016 Powered by cudou.com design MATCHINFO