0

array A: array('name','world cup','lang','ru'); array B: array('name'=>'world cup','lang'=>'ru'); How to convert array A into arrayB in the best way?

2
  • It’s so smart, but what if I have two elements in my array? Commented Jul 19, 2018 at 2:44
  • just use for loop Commented Jul 19, 2018 at 3:13

3 Answers 3

3

You can run a for-loop and generate the array.

While generating you need check if the next item is defined before adding it to array B.

$arrayA = array('name','world cup','lang','ru');

for($i=0; $i < count($arrayA); $i+=2){
    $arrayB[$arrayA[$i]] = isset($arrayA[$i+1]) ? $arrayA[$i+1] : '';
}

print_r($arrayB);
Sign up to request clarification or add additional context in comments.

1 Comment

since you're incrementing by two's you can just use isset alone, its understood that if +1 isn't set it means its the array is jagged (missing pair), no need for modulus, something like for loop and a simple ternary $arrayB[$arrayA[$i]] = isset($arrayA[$i+1])? $arrayA[$i+1] : '';
1

If you have arrays of varying sizes, and it's always in the order of key, value, key, value, ... you can make a function that converts it:

/**
 * Converts numeric array to key - value pairs in order
 *
 * @param array $arrayA
 * @return array $arrayB
 */
function convertArrays($arrayA)
{
    $keys = array(); //array to store keys
    $values = array(); //array to store values

    //seperate keys and values
    for($i = 0; $i < count($arrayA); $i++)
    {
        if($i % 2 == 0) //is even number
        {
            array_push($keys, $arrayA[$i]); //add to keys array
        }
        else //is odd number
        {
            array_push($values, $arrayA[$i]; //add to values array
        }
    }

    $arrayB = array(); //array for combined key/value pairs

    $max = count($keys);
    if(count($keys) != count($values)) //original array wasn’t even
    {
        $max = count($keys) - 1;
    }

    //join into single array
    for($j = 0; $j < $max; $j++)
    {
        $arrayB[ $keys[$j] ] = $values[$j];
    }

    return $arrayB;
}

2 Comments

What if you get array A not divisible by 2? This answer is buggy.
That’s what I said at the bottom. Only works if the array is always even. If the asker wants to modify it to check for all possibilities he/she can. This is just an example of how the code might look.
-1

if the format remains constant and you wont get more pairs:

$arrayA=array('name','world cup','lang','ru');
$arrayB=array($arrayA[0]=>$arrayA[1],$arrayA[2]=>$arrayA[3]);

print_r($arrayB);



Array
(
    [name] => world cup
    [lang] => ru

)

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.