I'm hoping someone can help I'm trying to find a way to find a value in an array exists like the PHP in_array
.
I have two variables PTOWN
and ADDRESS
. I want to find if the PTOWN
is anywhere in the array?
I'm hoping someone can help I'm trying to find a way to find a value in an array exists like the PHP in_array
.
I have two variables PTOWN
and ADDRESS
. I want to find if the PTOWN
is anywhere in the array?
Are you looking for PTOWN
in the keys or the values of the nodes? If PTOWN
might be found in the keys, you can use $ORDER to find the closest match to what you have. Let's say you have an array like this:
new PTOWN,Address,Array
set PTOWN="Paris"
set Address="Some address"
;
set Array("Paris")="123 Avenue Louis Pasteur"
set Array("Madrid")="434 Calle De Duermos"
set Array("Boston")="1522 Market Street"
;
if $ORDER(Array(PTOWN))=PTOWN d
...
$ORDER will return the key that matches your search term most closely and also comes after it in MUMPS' ordering system. So $ORDER(Array("Pa"))
returns "Paris", $ORDER(Array("Mad"))
returns "Madrid", and $ORDER(Array("Alameda"))
returns "Boston" because "Boston" is the next thing after "Alameda" in the array.
You can use this to loop over all the keys in the array, as well:
new nodeName
set nodeName="" ; you have to pass $ORDER "" to get the first thing in the array
;
for set nodeName=$ORDER(Array(nodeName)) quit:nodeName="" d
; $ORDER returns "" when you pass it the *last* key in the array, so we can quit this loop when we get that back
;
if nodeName=PTOWN write Array(nodeName)
If PTOWN
will be found in the values of the array, you'll have to use the loop method.
Assuming that PTOWN is '$needle' and ADDRESS is '$haystack' (as per in_array documentation), and without knowing the array format, the best you can do is something like:
in_array(needle,haystack)
NEW idx,found,subAry
SET found=0 ; If you want to return 0 instead of "" if not found
;
FOR $ORDER(haystack(idx)) QUIT:idx="" DO QUIT:found
. ; If the format of the array is: array(<index>)=<value>
. IF haystack(idx)=needle SET found=1 QUIT
. ;
. ; If the format of the array is: array(<key>)=<value>
. ; Note: this type of search can be made a bit more efficient, but we're brute-forcing here
. IF idx=haystack SET found=1 QUIT
. ;
. ; If you're using nested keys and values...this is NOT recommended since Cache doesn't really support recursion
. MERGE subAry=haystack(idx)
. SET found=$$in_array(needle,subAry)
;
QUIT found
You'd call it like so:
...=$$in_array(PTOWN,.ADDRESS) ; Don't forget to pass by reference!