Showing posts with label php. Show all posts
Showing posts with label php. Show all posts

Wednesday, July 23, 2008

assigned by value?


$myArray = array('key1'=>array('1', '2'), 'key2'=>array('3', '4'));
$subArray = $myArray['key1'];
array_push($subArray, '5');

The trick is that new value '5' is ONLY added to $subArray, but not to $myArray['key']. PHP's assignment operator '=' assigns value by copy. So $subArray is not really a sub-array of $myArray, it is a separate array. Assignment by reference is also supported, using the $var = &$othervar; syntax.

The same for the 'foreach' loop

foreach($myArray as $subArray)

As of PHP 5, foreach ($arr as &$value) is supported. This will assign reference instead of copying the value.

Monday, July 21, 2008

Utility Functions

1. Sorting with user defined comparator

In PHP -


usort($bp_radios, create_function('$a, $b',
'return $a["radio_index"] - $b["radio_index"];'));


In JS -

tabRF_apList[i]['radios'].sort(function(a,b) {
return a['radio_index'] - b['radio_index']});

2. Array <=> String with delimiter

In PHP -

$radio = implode('/', $radioNameArray); // {'a', 'b'} => 'a/b'
$radioNameArray = explode('/', $radio);

In JS -

var radio = radioNameArray.join('/');
var radioNameArray = radio.split("/");

Tuesday, July 8, 2008

dynamic variable

This article talks about different ways to compose dynamic Javascript variable -


eval('name' + i + ' = "Marco"'); // compose a string with variable as eval's argument
window['name' + i] = 'Marco';

And the PHP counterpart is:

${'name'.$i} = 'Marco';
echo 'ap_bVNSRadio_${vname}';