Tony Haynes
Tony Haynes

Reputation: 69

php match variable names using wildcard

I need to check for the existence of a variable.

Variables are not necessarily created in order 1.2.3. They could be created 2.4.3.1. These are also not created at the same time on the same page. So I am just wanted to check for the existence of the variable.

$_SESSION['rule1']
$_SESSION['rule2']
$_SESSION['rule3']
$_SESSION['rule4']

<?
 if(isset($_SESSION['rule'.*wildcard*'])) {

 do something

 }
?>

I'm not sure how to go about this. The answer probably lies in REGEX but I am horrible with REGEX.

Upvotes: 3

Views: 931

Answers (2)

x3ns
x3ns

Reputation: 520

Here is another solution with the use of preg_match:

function arrayHasSimilarKey(array $array, $matchKey)
{
    $pattern = '/' . str_replace('*', '.*', $matchKey) . '/i';
    foreach ($array as $key => $value) { echo $key.PHP_EOL;
        if (preg_match($pattern, $key)) {
            return true;
        }
    }

    return false;
}

$testArray = ['abc' => 1, 'test_1' => 1, 'test_2' => 1, 'test2_1' => 1, 'test3_2' => 1];
$tests = [
    0 => arrayHasSimilarKey($testArray, 'test*'),    // true
    1 => arrayHasSimilarKey($testArray, 'test2*_2'), // false
    2 => arrayHasSimilarKey($testArray, 'test3*'),   // true
    3 => arrayHasSimilarKey($testArray, 'test3*_1'), // false
    4 => arrayHasSimilarKey($testArray, '*_2')       // false
];

var_dump($tests);

In your case, $testArray would be $_SESSION

Upvotes: 1

astrangeloop
astrangeloop

Reputation: 1520

If you don't know need to know which rule* key is in the session array, only if any of them are present, then you could try this:

<?php

function prefixExists(array $assoc_array, $prefix)
{
    $length = strlen($prefix);
    foreach ($assoc_array as $key => $unused)
    {
        if (strncmp($key, $prefix, $length) === 0) {
            return true;
        }
    }
    return false;
}

Testing as follows:

session_start();
var_dump(prefixExists($_SESSION, 'rule'));
$_SESSION['rule3'] = 'some value from form';
var_dump(prefixExists($_SESSION, 'rule'));

Gives output:

bool(false)
bool(true)

Upvotes: 1

Related Questions