-1
Array
(
    [0] => string1
    [1] => string2
    [2] => string3
    [3] => string4
)

$key   = $string1;
$value = $string2;

$key = $value;

I am trying to figure out how to convert this array into an associative array starting from [0] being the $key and [1] being the $value throughout the entire array.

1

1 Answer 1

2

There are several ways you can do that, you can separate the odd and even elements of the array and then use array_combine() to make an associative array, or you can just iterate through the array leaping in pairs like this:

$array = array_values($array); // reset keys from input array to make sure they are contiguous
$result = [];
for ($i = 0; $i < count($array); $i += 2)
     $result[$array[$i]] = $array[$i + 1];
Sign up to request clarification or add additional context in comments.

5 Comments

This throws an error of "Warning: Illegal offset type in" for this line $result[$array[$i]] = $array[$i + 1];
@timeba Array keys can only be strings or numbers, looks like you have some element in your input array that is neither. You can try $result[(string)$array[$i]] instead of $result[$array[$i]] to workaround the problem, but something tells me you have a type there that doesn't convert to string that easily. Only debugging will tell.
Would dashes and white spaces make it a non string?
@timeba Don't think so.
Thank you for your help, it seems like the issue is the array is trying to output the outertext of the DOM tree im trying to parse instead of the innertext. When I output the original array before i try to manipulate it it shows the DOM innertext correctly. But for some reason when I try to manipulate the key and convert it to a string it outputs the DOM tree instead of the innertext.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.