INDEX |
---|
PHP - add item to beginning of associative array |
PHP sizeof() Function |
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 |
Comparing Dates in PHP |
Adding days to Date in PHP |
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:
$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); ?>
PHP sizeof() Function
The sizeof() function returns the number of elements in an array.<?php
$cars=array("Volvo","BMW","Toyota");
echo sizeof($cars);
?>
Example
for($i=0;$i<sizeof($batch);$i++){
echo '<td>'. $batch[$i]['batch_name'].'</td>';
}
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);
Comparing Dates in PHP
How to compare Dates in php
$exp_date = "2017-01-10";
$todays_date = date("Y-m-d");
$today = strtotime($todays_date);
$expiration_date = strtotime($exp_date);
if ($expiration_date > $today) {
echo "yes";
} else {
echo "no";
}
?>
Adding days to Date in PHP
<?php
$Date = date("Y-m-d"); // "2010-09-17";
echo date('Y-m-d', strtotime($Date. ' + 1 days'));
echo '<br>';
echo date('Y-m-d', strtotime($Date. ' + 360 days'));
?>