If value exist remove from exists

info from db
example one

$db = "13_7|56_7|2_1";

or like
example two

$db = "14_7";

now if get info like this (example one)

$check_if_exites = "56_7";

I NEED

function to check if exites and if yes remove this info + if like example one do Update, if like example two do DELETE the table ID

maybe this is will be help (taked from here ) thanks to fretburner

function serialize_prices_id(array $data){
    $output = array();
    foreach ($data as $id => $count) {
        $output[] = $id.'_'.$count;
    }
    return implode('|', $output);
}

function unserialize_prices_id($prices_string) {
    $data = array();
    foreach (explode('|', $prices_string) as $product) {
        list($id, $count) = explode('_', $product);
        $data[$id] = $count;
    }
    return $data;
}

Thanks

First, I must say that storing data like “abc|def|hij” is not a good idea and generally a sign of a bad DB design. Sorry, I had to say it :wink:

That being said, with both methods (serialize and unserialize), you should have all the tools you should need to achieve what you want.

With unserialize, you’ll end up with an array like:
13=>7
56=>7
2=>1

With serialize, it will take your array and create your string with the format you want (like 13_7|56_7 etc)

If you want to know if “13_7” exists in a string like 12_7|13_7|etc, you could do something like:


// checks if a product in the form of "xx_xx" exists in an array of products and count
function productExistsInArray($product, $arr) {
  list($id, $count) = explode('_', $product);  
  if (isset($arr[$id]) && $arr[$id] == $count)
            return true;

  return false;
}

// here's how to use the method:
$dbData = "13_7|56_7|2_1";

$existsInDb = productExistsInArray("56_7", unserialize_prices_id($dbData));

if ($existsInDb) {
 echo "exists";
} else {
 echo "doesn't exists";
}

Note that I didn’t tested this code but this should gives you a general idea :wink:

Big thanks xMog - Work!

I just change your function from return true; to unset($arr[$id]); and exactly what i need :-)))

function productExistsInArray($product, $arr){
  list($id, $count) = explode('_', $product);
  if (isset($arr[$id]) && $arr[$id] == $count){
       unset($arr[$id]);
  }
  return $arr;
}

//$dbData = "13_7|56_7|2_1";
$dbData = "56_7";
$existsInDb = productExistsInArray("56_7", unserialize_prices_id($dbData));

if(!empty($existsInDb)){
// update
 echo serialize_prices_id($existsInDb); //show new results
}else{
// delete because no data
echo 'nothing here';
}