0

Lets say I have an array:

array("item1", "item2", "item3");

And 3 variables:

$value1 = ""; 
$value2 = "";
$value3 = "";

How can I manipulate this array by changing their values to keys so that item1, item2, item3 are now keys and then set new values to them which are value1, value2, value3 in order.

I.e. it should end up with:

array("item1" => $value1, "item2" => $value2, "item3" => $value3);

thank you

3 Answers 3

1

What about the direct approach to create a new array?

$myArray = [
    "item1" => $value1,
    "item2" => $value2,
    "item3" => $value3,
];

This cannot really be "automated", since there is no relation between the key strings ("item1" ...) and the variable names ("value1" ...).

The only feature that may come in handy here is the array_combine() function:

<?php
$keys = ["item1", "item2", "item3"];
$value1 = "one";
$value2 = "two";
$value3 = "three";

$output = array_combine($keys, [$value1, $value2, $value3]);
print_r($output);

The output obviously is:

Array ( [item1] => one [item2] => two [item3] => three )

Sign up to request clarification or add additional context in comments.

Comments

0

you can do many solution for insert values into the array like this:

//array_push($arrayVar, <your Value> );
$arrayVar = array();

array_push($arrayVar, $value1 );
array_push($arrayVar, $value2 ); //ETC

but if you want to Read your array and save the Array value in your Variable you need to do something like this;

$ArrayVar = Array("item1", "item2", "item3");
//so you have 3 items values in 3 position  of 0 to 2, you can use it like this
$value1 = $ArrayVar[0]; //This Array position is "item1" so you can print it
Echo $value1;

output

item1

I hope you are useful, and whatever you are looking for otherwise if not I did not understand your request correctly.

Comments

0

store your values in an array and use array_combine() method of php.
like

echo array_combine($itemarray,$valuearray);

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.