Click to See Complete Forum and Search --> : [SUB] Print_r in ASP


DmitriF
04-11-2008, 10:14 AM
For those of you used to PHP, heres a function that mimics print_r. Doesnt quite
do multiple dimensions, but recursively visits nested arrays. Useful for debugging array values. Thought this might help someone out.

Usage: call print_r(arr3, 0)
Code:

public sub print_r(arr, depth)
if isArray(arr) then
If depth=0 then Response.Write ("<pre>" & Tab(depth)) end if
Response.Write ("Array <br />")
Response.Write (Tab(depth) & "(<br />")
for x=0 to uBound(arr)
if isArray(arr(x)) then
Response.write(Tab(depth+1) & "["&x&"] =>")
call print_r(arr(x), depth+2)
else
Response.write(Tab(depth+1) & "["&x&"] =>" & arr(x))
end if
Response.Write ("<br />")
next
Response.Write (Tab(depth) & ")")
If depth=0 then Response.Write ("</pre>") end if
end if
end sub
public function Tab(spaces)
val = ""
for x=1 to spaces
val=val & " "
next
Tab = val
end function


Example:

dim arr1: arr1 = Array(1, 2, 3, 4, Array(4, 1, 4, 6))
dim arr2: arr2 = Array(5, 6, 7, 8)
dim arr3: arr3 = Combine(arr1, arr2)

call print_r(arr3, 0)


Output:

Array
(
[0] =>1
[1] =>2
[2] =>3
[3] =>4
[4] =>Array
(
[0] =>4
[1] =>1
[2] =>4
[3] =>6
)
[5] =>5
[6] =>6
[7] =>7
[8] =>8
)

DmitriF
04-11-2008, 10:36 AM
Here are two more functions for you.
Combine -- Combines two arrays.
Unique -- Returns a new array that contains only unique keys, ignores nested arrays.

Combine (Usage:: x = Combine(arr1, arr2))

function Combine(byRef mArray1, byRef mArray2)
dim newArray()
dim iter: iter=0
redim newArray(UBound(mArray1) + UBound(mArray2) +1)
for x=0 to UBound(mArray1)
newArray(iter) = mArray1(x)
iter=iter+1
next
for x=0 to UBound(mArray2)
newArray(iter) = mArray2(x)
iter=iter+1
next
Combine = newArray
end function


Unique (Usage:: x = Unique(arr1))

function unique(byRef mArray1)
dim str: str = ""
dim newArray
for x=0 to UBound(mArray1)
if not isArray(mArray1(x)) then
if inStr(str, mArray1(x)) = 0 then
str = str & mArray1(x)
if not x=UBound(mArray1) then str = str&"," end if
end if
end if
next
newArray = split(str, ",")
unique = newArray
end function

russell
04-11-2008, 09:18 PM
nice. here's (http://www.webdeveloper.com/forum/showpost.php?p=684574&postcount=5) a couple of others that may be of interest :)

DmitriF
05-06-2008, 03:00 PM
Nice russell, any other anyone?