How to insert an item in a certain position of the php array?

3

I have the following array,

$status = array();
$status["Visualizar"] = "Visualizar";
$status["Editar"] = "Editar";
$status["Status"] = "Alterar Status";
$status["Boleto"] = "Gerar Boleto";

It turns out that depending on the current status that goes from 1 to 10 I should or should not show the Item $ status ["Status"], as well as if it resolves, but it happens that when I give an unset and then reinsert the item it goes to the end of the list, but I need it to stay in the original position before ticket

Example:

if ($codstatus == 3){
  $status["Status"] = "Alterar Status";
}else{
  unset($status["Status"]);
}

Is there an elegant way to do this or do I have to redo the entire array every time?

    
asked by anonymous 04.04.2017 / 20:17

2 answers

2

For what reason?

First, why do you need to be in a certain order since your array is associative?

Now, if you need to be in the correct order, you can use the array_splice function, see example:

<?php

$array = ['a', 'b', 'd', 'e'];
array_splice($array, 2, 0, 'c');

var_dump($array); //['a','b','c','d','e']

See example online: link

    
04.04.2017 / 20:27
2

Do as follows:

$status = [
    'Visualizar' => 'Visualizar',
    'Editar' => 'Editar',
    'Boleto' => 'Gerar Boleto'
];

// Define a chave => valor que será inserido no array
$pair = ['Status' => 'Alterar Status'];

// Procura no array pela chave e retorna o índice dela
$afterIndex = array_search('Boleto', array_keys($data));

// Cria um novo array, repartindo o antigo em duas partes e adicionando o novo par de chave => valor entre elas
$newStatus = array_merge(array_slice($status, 0, $afterIndex-1), $pair, array_slice($status, $afterIndex-1));

print_r($newStatus);

Output:

Array
(
    [Visualizar] => Visualizar
    [Editar] => Editar
    [Status] => Alterar Status
    [Boleto] => Gerar Boleto
)
    
06.04.2017 / 15:31