Jump to content

How to use array_search for 1 sized array?


Tjorriemorrie

Recommended Posts

I have problems figuring this out. I expect it to remove the number and set the cookie again, but it gives this error:

 

Quest 132 not found in obtained:

Error in search!

array(1) {

  [ 0 ] =>

  string(3) "132"

}

 

Here's the code:

// remove qst, implode, and set
reset($obtained);
if ($key = array_search($questID, $obtained)) {
  unset($obtained[$key]);
  $adjObtained = implode(" ", $obtained);
  if (setcookie("obtained$s", $adjObtained, time()+86400*30)) {
    $goto = "setquests.php?sel=" . $s . "&drop=" . $questID;
    header("Location: $goto");
  } else {
    echo '<h1>Cookie could not be set!</h1>';
    ?><pre><?php var_dump($adjCompleted); ?></pre><?php
    exit;
  }
} else {
  echo "<h1>Quest $questID not found in obtained:</h1>";
  ?><pre><?php var_dump($obtained); ?></pre><?php
  exit;
}

 

Can anyone please help? It seems as soon as

the array is only 1 size big, it can't find the

value...or maybe it can't find the first value...

sigh, please help

Thanks rhodesa!! that explains it!

 

OK, but it is not to say the result will be the first key, it could stretch into thousands in the end. So my code was all wrong, coz it has that error if it's the first record and returns 0 which equates to false.

 

Is this better?

if (array_search($questID, $obtained)) {

  $key = array_search($questID, $obtained);

  etc

 

Also, can I now take out the reset($array); ?

[sOLVED]

 

// get key
if ($key = array_search($questID, $obtained)) {
  $found = true;
} elseif ($obtained[0] == $questID) {
  $key = 0;
  $found = true;
} else {
  $found = false;
}

//remove if found
if ($found) {
  unset($obtained[$key]);

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.