0

I need to suffix array values which will in fact be a tag CSS, so I need to suffix one array with :hover and another with :focus

$elements = array('.one','.two','.three');

desired new arrays

$helements = array('.one:hover','.two:hover','.three:hover');
$felements = array('.one:focus','.two:focus','.three:focus');

I know I can do it with a loop but question is, is there a fast one liner for this?

Benn
  • 4,840
  • 8
  • 65
  • 106
  • Always the same value for every element of the array? – napolux May 25 '16 at 16:16
  • @Napolux, yes , it will be either :hover, or :focus suffix – Benn May 25 '16 at 16:17
  • 1
    You can probably use `array_map` or even `array_walk` for this. – gen_Eric May 25 '16 at 16:17
  • 1
    Why are you looking for a "fast oneliner"? Do you think it'll work any better or faster than a plain old loop? – CodeCaster May 25 '16 at 16:22
  • @CodeCaster , good question , is array_map, array_walk going to be faster than the loop? – Benn May 25 '16 at 16:28
  • The real question is: are you going to notice it? If you really want to know, benchmark it. Otherwise, go for the most readable code. Chances are that a few string operations are going to have an immeasurably small impact on your entire code. – CodeCaster May 25 '16 at 16:29
  • @CodeCaster, is much more that 3 , that was just an example. Working on CSS generator and it can be well over 100 elements which is not much but for a loop search /replace it might be. – Benn May 25 '16 at 16:31
  • 1
    You can use regex. like [Regex to Add a postfix to each item of a PHP array](http://stackoverflow.com/questions/42691789/regex-to-add-a-postfix-to-each-item-of-a-php-array) – MahdiY Mar 09 '17 at 13:22

2 Answers2

5
$newelements = array_map(function($x){ return $x . ':hover'; }, $elements);
cmorrissey
  • 8,493
  • 2
  • 23
  • 27
4

You can alter the array itself (like my solution) or create a new array like in the other answer. Your choice. ;)

You can just pass the $item as reference in order to change the original array directly.

$array = ["test1", "test2", "test3"];
array_walk($array,function(&$item) {$item .= ':hover';});

The result is:

var_dump($array);

array(3) {
  [0]=>
  string(11) "test1:hover"
  [1]=>
  string(11) "test2:hover"
  [2]=>
  string(11) "test3:hover"
}
Community
  • 1
  • 1
napolux
  • 15,574
  • 9
  • 51
  • 70