-1

I need to remove a parameter within an array, change the value, then put it back into the array.

This is how I'm initially getting the values:

<?php
  $value = $_POST['criteria'];

  $valueSet = isset($value['countries']) ? $value['countries'] : '';
  $valueSplit= explode(",", $valueSet);
  $valueFinal = "'". implode("','", $valueSplit) . "'";

  echo $valueFinal;
?>

Using the above, the $valueFinal variable can look like this:

'USA','CAN','FRA'

I need to be able to check if 'FRA' exists in the array, remove it from the array, change it to 'GER', then put it back into the array.

In the end, the $valueFinal array should look like this:

'USA','CAN','GER'

I am not sure if this is possible. How can I make this work?

Edit

I am able to use the following to check if the value exists:

if(in_array("FRA", $valueSplit)

But I am not sure how to update that single value, then add it back to the array.

halfer
  • 19,824
  • 17
  • 99
  • 186
John Beasley
  • 2,577
  • 9
  • 43
  • 89

1 Answers1

1

You don't need to remove and put back an array element. You simply find the position of the element, and replace it by assigning to the same index.

Use array_search() to find the index of the old string in the array. If it finds it, reassign the element.

$index = array_search('FRA', $valueSplit);
if ($index !== false) {
    $valueSplit[$index] = 'GER';
}

Make sure you use !== rather than !=, since 0 is a valid index and it compares equal to false with type juggling.

Barmar
  • 741,623
  • 53
  • 500
  • 612
  • Satisfy my curiosity: Which part of this is not obvious? – Barmar Feb 08 '21 at 17:14
  • Please forgive my lack of knowledge. I have never done anything like this before. I was able to use in_array to check if the value exists. But I was not sure how to update the actual value and/or place it back into the array. – John Beasley Feb 08 '21 at 17:17
  • Any tutorial on PHP arrays should mention `array_search()`. – Barmar Feb 08 '21 at 17:18
  • @mickmackusa All the mega-dupes are about removing, but the question is about replacing. I admit that they're similar, but I didn't have either of these in my list of common dupes. – Barmar Feb 13 '21 at 17:10
  • Okay, I changed to a better dupe. – mickmackusa Feb 13 '21 at 17:46
  • @mickmackusa Thanks, I've saved both dupes for the future – Barmar Feb 13 '21 at 17:48