Menus

Friday, 16 October 2015

PHP Programming Tips


INDEX
PHP - add item to beginning of associative array
Split multiple lines and input them in separate row in a database
How to print a debug log
PHP prepend leading zero before single digit number
Show a number to 2 decimal places





PHP - add item to beginning of associative array


How can I add an item to the beginning of an associative array? 

For example, say I have an array like this:
$arr = array('key1' => 'value1', 'key2' => 'value2');

Answers:

You could use the union operator:

$arr1 = array('key0' => 'value0') + $arr1;

One way is with array_merge:
<?php
$arr = array('key1' => 'value1', 'key2' => 'value2');
$arr = array_merge(array('key0' => 'value0'), $arr);  ?>




Split multiple lines and input them in separate row in a database



How to explode a multi-line string?


PHP explode() Function

Definition and Usage

The explode() function breaks a string into an array.

Syntax

explode(separator,string,limit)




Depending on your os a newline can be "\n", "\r\n" or "\r".
Give this a shot:
$strip=explode("<br>", nl2br($linkfield));
or maybe safer:
$strip=explode("\n", str_replace(array("\n", "\r\n"), "\n", $linkfield));


$address=explode("\n", str_replace(array("\n", "\r\n"), "\n", $student->present_address));
print_r($address);

Output

 Array ( [0] => SHANEESH P [1] => OPP MUNICIPAL OFFICE [2] => MALAPPURAM [3] => KERALA [4] => INDIA )


<?php
$text = $_POST['userlist'];
$array = explode('\n', $text);
?>



How to print a debug log


file_put_contents('your_log_file', 'your_content');
or
error_log ('your_content', 3, 'your_log_file');

Example 

file_put_contents('error_log', $userid);

Value stored to error_log file in your folder.



PHP prepend leading zero before single digit number


str_pad($number, 2, '0', STR_PAD_LEFT); 

Add zero to before number.

<?pph

$m=1;

$p= str_pad($m, 3, '0', STR_PAD_LEFT);

echo $p;

?>

Output : 001



show a number to 2 decimal places


You can use number_format():
return number_format((float)$number, 2, '.', '');

$padded = sprintf('%0.2f', $unpadded);

echo round(5.045, 2); 



1 comment:

  1. Being a PHP developer, one needs to know all the high & lows related to PHP development process as it decides how efficiently a project undertaken from a client will be delivered. Gathering proper knowledge of the project requirements, keeping error reporting ON, deliberate & accurate coding etc., are some of the ways that will ensure that the PHP project one undertakes is delivered successfully.

    php training in Chennai

    ReplyDelete