0

I stored a variable i exploded into an array into a session.

$totalSlip = explode(',',$_SESSION['isSlip']);

this gives me an array of

  Array ( 
    [0] => 25$$A 
    [1] => 34$$D 
    [2] => 32$$D 
  )

There are 3 values that are possible e.g 25$$A, 25$$D and 25$$H. My challenge is i want the a new value to substitute the value of a key in the array when it occurs more than once. e.g if 25$$A already exist and i add 25$$D what it gives me is

Array ( 
    [0] => 25$$A 
    [1] => 34$$D 
    [2] => 32$$D 
    [3] => 25$$D
  )

but what i want is this

Array ( 
    [0] => 25$$D
    [1] => 34$$D 
    [2] => 32$$D
  )

i want the value of array[0] to be replaced. I'll appreciate any help i can get, thanks.

James
  • 20,957
  • 5
  • 26
  • 41
Ifeoluwapo Ojikutu
  • 69
  • 1
  • 1
  • 12
  • 5
    Also, why are you using string concatenation then exploding it later? You can store arrays in PHP sessions. –  May 11 '14 at 21:07

1 Answers1

2

If possible, you need to change your logic to use the arrays this way. Have the integer to be the array key and the character, to be the value. So, your array:

Array ( 
    [0] => 25$$A 
    [1] => 34$$D 
    [2] => 32$$D 
)

Should look something like this:

Array (
    [25] => A 
    [34] => D 
    [32] => D 
)

This way, you can just make changes to the logic by updating the key with this:

$array[25] = "D";

And this makes the below if the array key exists:

Array (
    [25] => D 
    [34] => D 
    [32] => D 
)

Or if it doesn't exist, it creates one! For eg:

$array[65] = "A";

Array (
    [25] => A 
    [34] => D 
    [32] => D 
    [65] => A 
)
Praveen Kumar Purushothaman
  • 164,888
  • 24
  • 203
  • 252