简体   繁体   中英

compact() variables into array by prefix?

Is this possible?

Like make an array with all the variables that have a certain prefix?

I don't need the keys just the values, but I guess I could use array_values on the array.

If you need to do this, it's probably not written very well to begin with, but, here's how to do it :)

$foobar = 'test';
$anothervar = 'anothertest';
$foooverflow = 'fo';
$barfoo = 'foobar';

$prefix = 'foo';
$output = array();
$vars = get_defined_vars();
foreach ($vars as $key => $value) {
    if (strpos($key, $prefix) === 0) $output[] = $value;
}

/*
$output = array(
    'test', // from $foobar
    'fo', // from $foooverflow
);
*/

http://php.net/manual/en/function.get-defined-vars.php

我的眼睛有点流血,但我无法抗拒一根眼线。

print_r(iterator_to_array(new RegexIterator(new ArrayIterator(get_defined_vars()), '/^' . preg_quote($prefix) . '/', RegexIterator::GET_MATCH, RegexIterator::USE_KEY)));

If you're talking about variables in the global scope, you could do this with $GLOBALS[] :

$newarray = array();

// Iterate over all current global vars 
foreach ($GLOBALS as $key => $value) {
  // And add those with keys matching prefix_ to a new array
  if (strpos($key, 'prefix_' === 0) {
    $newarray[$key] = $value;
  }
}

If you have lots and lots of variables in global scope, this is going to be slower in execution than manually adding them all to compact() , but faster to type out.

Addendum

I would just add (though I suspect you already know) that if you have the ability to refactor this code, you are better off to group the related variables together into an array in the first place.

This, my second answer, shows how to do this without making a mess of the global scope by using a simple PHP object:

$v = new stdClass();
$v->foo = "bar";
$v->scope = "your friend";
$v->using_classes = "a good idea";
$v->foo_overflow = "a bad day";

echo "Man, this is $v->using_classes!\n";

$prefix = "foo";
$output = array();
$refl = new ReflectionObject($v);
foreach ($refl->getProperties() as $prop) {
        if (strpos($prop->getName(), $prefix) === 0) $output[] = $prop->getValue($v);
}

var_export($output);

Here's the output:

Man, this is a good idea!
array (
  0 => 'bar',
  1 => 'a bad day',
)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM