Add elements in Associative Array - PHP

Asked

Viewed 1,084 times

-2

In a typed array just count the number of array elements and pass this value as index. But and in a one-dimensional associative array, as I add new elements?

My array is:

$array ['chave1'] = $valor1;
$array ['chave2'] = $valor2;

I know the array_push function but it cannot assign a new key to an element and in the array I need, each element will have a new key.

  • 3

    Wow.... $array['chave3'] = $valor3; .... $array['chaveN'] = $valorN;

  • It would be the same as $array = array("chave1" => $valor1,"chave2" => $valor2,"chave3" => $valor3, ... , "chaveN" => $valorN)

  • https://repl.it/JaQA/1

  • Marceloboni has already answered you there.

  • Each element must be inserted separately (at different times. Without specifying the order of the elements, one element ends up rewriting the other.

  • 2

    There’s no sense of it, either you better specific your doubt and your problem, or else that you said has no sense at all

Show 1 more comment

1 answer

0

I believe that’s it; to put a new value just put it in value

    $vetor = array();
    $keys = array_keys($vetor);
    $values = array_values($vetor);
    $result = array();
           foreach ($keys as $i => $k) {
             $result[$k][] = $values[$i];
           }
    return  $result;

Browser other questions tagged

You are not signed in. Login or sign up in order to post.