0

Suppose we have an array with one attribute for each element:

Array ( [0] => A [1] => B [2] => C [3] => D ) 

Is it possible to add the same uniform attribute to each of the elements, so that a new two-dimensional array would be obtained? I.e. for attribute X:

Array ( [0] => Array ( [0] => A [1] => X)
        [1] => Array ( [0] => B [1] => X)
        [2] => Array ( [0] => C [1] => X) )

I know, I could do it using for each loop, but is there any more elegant solution (such as array_combine)?

(For assigning different values, please refer to: Assigning a value to each array element PHP)

1
  • 1
    Well, you could use array_merge by typecasting the current value to an array, merge it with an array with "X" allready in there for a single value. Use array_walk to apply this to all parts of the origional array. But I strongly doubt this is worth the effort. What's wrong with good old for loop? Would probably be clearer and cleaner then a very complicated, intelligent looking one-liner. In the end some code back there WILL loop over your initial array, so its not more efficient. Commented Dec 11, 2011 at 14:29

2 Answers 2

5

You could use array_map:

$array = array ( 'A', 'B', 'C', 'D' );
$array = array_map(function($el) {
  return array($el, 'X');
}, $array);
Sign up to request clarification or add additional context in comments.

Comments

1

array_walk could work as well.

$arr = array('A', 'B', 'C', 'D');
array_walk($arr, 'arrFunc');
function arrFunc(&$item, $key)
{
    $item = array($item, 'X'); 
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.