0

I have the following array:

Array
(
    [name] => hejsan
    [lastname] => du
)

I'm trying to loop through every item in the array, and store the name of the item in the array, and the value of that item, in two seperate strings.

Something like this:

$name1 = "name";
$value1 = "hejsan";

$name2 = "lastname";
$value2 = "du";

Is that possible?

Thanks in advance!

2 Answers 2

3

You can use a foreach to loop through the key=>value pairs of an associative array:

foreach ($array as $key=> $value) {
  // Set the strings here
}

However, have you considered how you're going to store these string values as variables? You will either need to use dynamically named variables, which are (imo) messy, or you will want to use two arrays to store the keys and values anyway. If you're just going to use two arrays, you may as well take advantage of PHP's inbuilt array functionality:

$array = // your associative array
$arrayKeys = array_keys($array); // the keys
$arrayValyes = array_values($array); // the values

So, with this, $name1 would be $arrayKeys[0], $value1 would be $arrayValues[0], and so on. Note that yes, this may (I don't know how array_keys/array_values are implemented) be less efficient than a single loop through, but unless your array is massive that is not going to be a problem at all.

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

Comments

2

Use foreach:

foreach ($array as $keyname => $data) {
// Do whatever
}

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.