Jump to content

Small array search just fails


gearsgod

Recommended Posts

I keep getting these errors, running php 5.4;

Notice: Undefined variable: value in C:\xampp\htdocs\BK\functions.php on line 133

Warning: Creating default object from empty value in C:\xampp\htdocs\BK\functions.php on line 133

Fatal error: Cannot access empty property in C:\xampp\htdocs\BK\functions.php on line 133

 

and heres my code;

128 function array_find($parents, $searched) {
129  if (empty($searched) || empty($parents)) {
130    return false;
131  }
132
133  foreach ($parents as $key -> $value) {
134    $exists = true;
135    foreach ($searched as $skey -> $svalue) {
136      $exists = ($exists && IsSet($parents[$key][$skey]) && $parents[$key][$skey] == $svalue);
137    }
138    if($exists){ return $key; }
139  }
140
141  return false;
142 }
Link to comment
https://forums.phpfreaks.com/topic/297232-small-array-search-just-fails/
Share on other sites

 

Unless you are in the context of a class with an object, I think you're looking for this:

foreach ($parents as $key=>$value) { // -> is for class pointers as in $this->object

The errors are gone, but now it does not find conflicts in an array and point out the key for it

:/

example:

Array ( [0] => Array ( [0] => 12 [1] => 12 [2] => 1pm ) [1] => Array ( [0] => 13 [1] => 13 [2] => 1pm ) )

as you can see, they both are set at 1pm, it needs to return a true, but my script thinks its still false

foreach ($searched as $skey -> $svalue) {
    $exists = ($exists && IsSet($parents[$key][$skey]) && $parents[$key][$skey] == $svalue);
}
if($exists){ return $key; }
$exists is only ever going to be equal to the last iteration. So if your last iteration is true, it'll be true - otherwise if the last iteration is false, it'll be false. This will effectively ignore every other iteration.

 

I'm not really sure what your logic is trying to do here, but I think you need to break from the foreach loop.

Are $parents and $searched two different arrays?  I can't tell from your logic whether these are two different arrays or different dimension of a multi dim array.  The multi dim array above has two dimensions.  Is that your $parent (first dimension) and $searched (second dimension).  If so, your outer and inner loops maybe confusing the logic.  Maybe try a for loop on the inner to help keep things simpler and more manageable.

You probably want the return WITHIN your foreach() loop if it finds the value

foreach ($searched as $skey => $svalue) {
  if(isset($parents[$key][$skey]) && $parents[$key][$skey] == $svalue) {
     return $key; //return the key we found
  }
}
return false; //didn't find key

also, you probably want "isset()", not "IsSet()"

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.