Reputation: 4457
Is it possible to do something like this in PHP?
$array = array(
array(
'key1' => 'Lorem ipsum dolor sit amet, consectetur adipisicing elit.',
'key2' => custom_function(key1),
'key3' => 'Dolores quas quis beatae. Quis modi nulla aspernatur cumque cum atque deleniti provident.',
),
array(
'key1' => 'Lorem ipsum dolor sit amet, consectetur adipisicing elit.',
'key2' => custom_function(key1),
'key3' => 'Dolores quas quis beatae. Quis modi nulla aspernatur cumque cum atque deleniti provident.',
),
array(
'key1' => 'Lorem ipsum dolor sit amet, consectetur adipisicing elit.',
'key2' => custom_function(key1),
'key3' => 'Dolores quas quis beatae. Quis modi nulla aspernatur cumque cum atque deleniti provident.',
),
);
instead of typing twice the same value in both keys?
What I'm trying to do is to set the value of key2 properly during the creation of the array and not do this insead after I have created the array
$array['key2'] = my_custom_function($array['key1']);
Upvotes: 0
Views: 90
Reputation: 4584
Well, not with that exact syntax and actually I am not sure if you are able to do this during the creation of the array.
What you're trying to do is set value B equal to value A in the array, there's something else you could do which would be to store the contents of value A in a variable before putting it in the array like this:
$myValue = 'some lorum ipsum text'
$myArray = [
'key1' => $myValue,
'key2' => myFunction($myValue)
//...
];
This way you don't have to use the method you want to avoid and it will probably be less error prone than trying to do it in the array itself even if it works perfectly fine ;)
EDIT 1
The OP has a nested array with more arrays in them containing the key / value pairs that need to be duplicated.
What we do here, if I make the assumption that key1
is always the main value and key2
is always the value you'd like to duplicate:
foreach ($array as $singleArray) {
//$singleArray is now $array[i] where i = n of times looped
//also note that $singleArray['key1'] exists here.
$myValue = $singleArray['key1'];
//here we update 'key2' of the array to match 'key1' after executing a function on it's value
$singleArray['key2'] = myFunction($myValue);
}
If your keys already exist in the array before you start this loop.
e.g. your arrays are filled within the main array
Then you can safely do this.
Do note that anything in $singleArray['key2']
will be overridden per sub-array.
Upvotes: 2
Reputation: 7662
You need to define an array first. How to create an array?
$array = array(
'key1' => 'Lorem ipsum dolor sit amet, consectetur adipisicing elit.',
'key2' => '', // has same value like key1
'key3' => 'Dolores quas quis beatae. Quis modi nulla aspernatur cumque cum atque deleniti provident.',
);
To change the value of $array['key1']
to $array['key1']
echo $array['key2'] = $array['key1'];
NOTE
You need to define my_custom_function()
by your end as you told on your comment! It is for formatting
Upvotes: -1