Accessing PHP arrays in an extension
The PHP runtime allows an extension to receive an Array as a parameter and provides several interfaces to access and update the elements of that array. New arrays can also be created. This tutorial shows how to create an extension function which takes two arrays as parameters and returns an array containing the bigdecimal sum of elements in the two arrays which have the same integer key. Elements without integer keys or with keys which do not appear in the other array are ignored.
1. Add the following Java™ code to the BigDecimalExtension class:
@XAPIExtension("BigDecimal")
public class BigDecimalExtension extends ExtensionBaseImpl {
@XAPIFunction("array_add_bigdecimal")
public void array_add_bigdecimal(RuntimeContext ctxt) {
// firstArray and secondArray will refernce PHP arrays that already exist in the PHP runtime
XAPIArray firstArray = ctxt.getArrayArgument(0);
XAPIArray secondArray = ctxt.getArrayArgument(1);
// returnArray will reference a newly created array that we will return to PHP.
XAPIArray returnArray = ctxt.createArray();
Iterator iter = firstArray.iterator();
while (iter.hasNext()) {
Object key = iter.next();
// key will be either an Integer or an XAPIString
// We are only interested in integers for this example
if (key instanceof Integer) {
XAPIString value1 = (XAPIString)firstArray.get(key, false, XAPIValueType.String);
// The third parameter to get specifies the type to coerce the value to
// Any PHP Type can be coerced to a string...
if (secondArray.containsKey((Integer)key)) {
XAPIString value2 = (XAPIString)secondArray.get(key, false, XAPIValueType.String);
BigDecimal arg1 = new BigDecimal(value1.getString());
BigDecimal arg2 = new BigDecimal(value2.getString());
BigDecimal result = arg1.add(arg2);
returnArray.put(key, result.toString());
}
}
}
ctxt.setReturnValue(returnArray);
}
}
2. Change the sample.php code to exercise the new function.
<?php
$a = array ('1'=>'111111111111111','2'=>'222222222222222','3'=>'333333333333333','4'=>'444444444444444');
$b = array ('2'=>'111111111111111','3'=>'222222222222222','4'=>'333333333333333','1'=>'444444444444444');
var_dump(array_add_bigdecimal($a,$b)); ?>
3. Run the IBM® WebSphere® sMash application and point a Web browser at http://localhost:8080/sample.php.
4. The Web browser displays the result:
array(4) {
[1]=>string(15) "555555555555555"
[2]=>string(15) "333333333333333"
[3]=>string(15) "555555555555555"
[4]=>string(15) "777777777777777"
}