Question

I have the next string:

$string = "3-6M: 5, 60: 1;";

What I need to do is to search for duplicates and iterate values for sizes (i.e. 3-6M) or append values if new size.

Example: 3-6M: 5, 60: 1; and the next value I need to add to the string is "3-6M: 2", if I search for it through strpos it will show me that it exists, how could I iterate with the existing value so that I will have in the end

3-6M: 7, 60: 1;

The appending stuff is here:

$size_f = $string;
$to_add[0] = "3-6M: 2";
if (strpos($size_f, $to_add[0])) {
// iterate
//echo "found";
} else {
// append
$size_f .= ", ".$to_add[0].":".$to_add[1];
}

Could you please help me, please?

Thank you

No correct solution

OTHER TIPS

If your are using array (you can create an array by exploding your string) :

// Your existing array of values
$initialArray= array('3-6M: 7', '60: 1');

// Array of value you want to add
$newValues = array('3-6M: 2', 'toto', '3-6M: 2');

foreach($newValues as $newValue) {
  if (in_array($newValue, $initialArray)) {
    echo "found";
  } else {
    array_push($initialArray, $newValue);
  }
}

Will print :

foundarray(4) {
  [0]=>
  string(7) "3-6M: 7"
  [1]=>
  string(5) "60: 1"
  [2]=>
  string(7) "3-6M: 2"
  [3]=>
  string(4) "toto"
}

Hope this solution is helpful.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top