How to construct an expression with many variables with the same name pattern?
P粉310931198
P粉310931198 2023-09-16 11:26:25
0
1
809

I have 50 variables in my system script. All of them have the same naming scheme, for example:

$case_un
$case_deux
$case_trois
...
$case_fourthy

I need to build an expression with all these variables without having to write code with 50 variable names!

Since all my variable names start with the "case_" pattern, is there a syntax to sum them or another expression?

I need to perform something like this:

$test_of_cases = $case_un && $case_deux && $case_trois && ...........$case_fourthy ;

And that thing:

$total_of_sums = $sum_un + $sum_deux + ............$sum_fifthy ;

So, is there a way to code in PHP? In formal language I just need to sum all variables whose names start with 'case_'.

My 50 variables cannot be stored in an array because they come from different sources and expression results.

I'm not sure, but I think there is an expression to do this in other languages:

LET a=SUM (`*case_*`)
    LET b=XOR (`*case_*`)
    LET c=AND (`*case_*`)

I learned this in my studies 30 years ago...

I hope PHP can do this, otherwise it won't work and I'll have to write 50 lines of code!

Sincere regards

P粉310931198
P粉310931198

reply all(1)
P粉956441054

Suppose you have an array like this

$arr = [
    'people_physic_eyes' => 1,
    'people_physic_weight' => 2,
    ...
    'name' => 'james',
    'age' => 15,
    ...
];

You want to sum all values ​​whose key name starts with "people_physical_", there are many ways to achieve this, here is one using array_reduce:

$sum = array_reduce(
    array_keys($arr),
    function ($sum, $key) use ($arr) {
        # if the key starts with 'people_physic_', sum up the value
        return strpos($key, 'people_physic_') === 0 ? $sum + $arr[$key] : $sum;
    },
    0
);

But this is not efficient because you have to compare all keys on every call.

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template