PHP

PHP


Datetime value to string in PHP

8.06.2010 | 0 Comments

This one escapes me everytime I need which results to much googling. The function is to convert SQL datetime value to human-readable format.


/* 
*   Converts the likes of '2010-08-01 14:57:15' to 'August 1, 2010, 2:57 pm' 
*/  
$datetime_value ="2010-08-01 14:57:15";
echo date(  "F j, Y, g:i a", strtotime( $datetime_value ) );  

Here’s another example which you will see on some of my templates.

<?php echo date('Y-m-d', strtotime('next month')); ?>

For more formats, go head to PHP Doc.

Reference:

http://php.net/manual/en/function.date.php


How to Get Apache & PHP version in Shell

8.05.2010 | 0 Comments

Aside from using phpinfo(), you can also use some shell commands to view the apache or php versions you are using.

NOTE: This is in CentOS 5.
Read more…


Adding New Array Key in PHP

4.02.2010 | 0 Comments

In adding a new array key, we’ll need to know two array functions called array_key_exists and array_merge.

First, let’s take a look at array_keys. It’s a function that returns an array containing the keys of an array.

<?php
$a = array("foo"=>"1","bar" => "2");
$keys = array_keys($a);

print_r($keys);
?>

Second, of course, is array_merge. As the name implies, it just merge the two array.

<?php
$a = array("foo" => "1", "bar" = "2");
$b = array("name" => "Juan", "gender" => "male");
$c = array_merge($b, $a);

print_r($c);
?>

So here’s the final code we have.

<?php
$a = array("foo" => "1", "bar" = "2");
// keys to be added
$b =array("name" => "Juan");
$c =array("gender" => "male");

$a = array_merge($a, $b, $c);

print_r($a);

?>

The code above is too simplistic ( we didn’t even use the array_keys function) but if you are not certain with the keys you of the array to be merged, then this functions become handy. Example as below.

<?php
$a = array("foo" => "1", "bar" = "2");
/* let's say $b comes from a function that returns
array with (i.e, array("name" => "Juan", "gender" => "male"))
*/
$b = my_function_ret_array();

$keys = array_keys($b);
foreach($keys as $key){
if(array_key_exists($key, $a){
$a[$key] = $b[$key];
}
else {
$a = array_merge($a, array($key => $b[$key]));
}
}

print_r($a);

?>

Again, I must remind my readers that there might be better way of doing this. It all depends on the situation and for the time being, this is the functions I used. If you want to suggest a new one, please share it in the comment box.


How to Find PHP.INI Path

9.05.2009 | 0 Comments

If you can’t find it in /etc/php.ini, then you have to use ssh and execute the command below.
php -i | grep php.ini

The command will return something like
Configuration File (php.ini) Path => /etc/php.ini