Thursday, January 29, 2009

Merging Arrays Preserving the Numeric Keys

Merging arrays like this:

<?php
$array1 = array();
$array2 = array(1 => "data");
$result = array_merge($array1, $array2);
?>

will result to:

Array
(
[0] => data
)

Don't forget that numeric keys will be renumbered!

If you want to completely preserve the arrays and just want to append them to each other (not overwriting the previous keys), use the + operator:

<?php
$array1 = array();
$array2 = array(1 => "data");
$result = $array1 + $array2;
?>

The numeric key will be preserved and thus the association remains.

Array
(
[1] => data
)

Source: http://php.net/array_merge

Tuesday, January 27, 2009

Empty Options for cakePHP 1.2

$options['empty'], if set to true, forces the input to remain empty.

When passed to a select list, this creates a blank option with an empty value in your drop down list. If you want to have a empty value with text displayed instead of just a blank option, pass in a string to empty.

<?php echo $form->input('field', array('options' => array(1,2,3,4,5), 'empty' => '(choose one)')); ?>

Source: http://book.cakephp.org/view/201/options-empty

How to Include Javascript File in Cake PHP

If you want to use a Javascript file, you usually reference it in the head section of your layout:


<head>
<?php echo $javascript->link('script.js'); ?>
</head>


But sometimes you want to use a certain Javascript file only in one view. Then it doesn’t make sense to reference it in the layout. You could take the PHP statement from above and place it in your view, that will work. But it is not a clean solution as the Javascript reference is placed somewhere in the middle of the generated HTML code.

Fortunately, CakePHP 1.2 allows you to define a reference to a Javascript file which is then added to the head section of the generated HTML code. For this purpose the variable $scripts_for_layout has to be added to the layout:


<head>
<?php echo $scripts_for_layout; ?>
</head>



In the view you can now link to the Javascript file with:

$javascript->link('script.js', false);

Notice the second parameter. Set it to false to tell cake to put the reference in $scripts_for_layout variable in the layout file.

Source: http://cakebaker.42dh.com/2007/02/21/referencing-javascript-files/

PHP Ternary Operator

Consider the following snippet of code:


if (condition){
variable = value1;
}else{
variable = value2;
}


Instead of doing that way, we can just simply do it like this:

variable = condition ? value1 : value2;


Another variation of using the ternary operator would be from:


if (condition){
echo "something1";
}else{
echo "something2";
}


And it can be expressed like:

echo condition ? "something1": "something2";


You can also nest the condition:

variable = cond0 ? (cond1 ? value1.1 : value1.2) : (cond2 ? value2.1 : value2.2);


Just use your imagination on how to use this form.