<?php
/**
* Function to add timestamp metadata to a given data item.
*
* @param mixed $data The data item to add metadata to. Can be anything.
* @param string $key The key for the timestamp metadata (e.g., 'created_at', 'modified_at').
* @return mixed The data item with the added timestamp metadata.
*/
function addTimestampMetadata($data, $key = 'created_at') {
// Get the current timestamp.
$timestamp = time();
// Add the timestamp metadata to the data item.
if (is_array($data)) {
$data[$key] = $timestamp;
} else {
$data = [$key => $timestamp]; // Wrap in array if not already
}
return $data;
}
/**
* Function to update the timestamp metadata of a data item.
*
* @param mixed $data The data item to update.
* @param string $key The key for the timestamp metadata.
* @return mixed The data item with updated timestamp metadata.
*/
function updateTimestampMetadata($data, $key = 'modified_at') {
$timestamp = time();
if (is_array($data)) {
$data[$key] = $timestamp;
} else {
$data = [$key => $timestamp];
}
return $data;
}
// Example Usage:
$my_data = "This is some data.";
$data_with_timestamp = addTimestampMetadata($my_data, 'created_at');
echo "Created at: " . $data_with_timestamp['created_at'] . "\n";
$array_data = ['name' => 'Example', 'value' => 123];
$array_data_with_timestamp = addTimestampMetadata($array_data, 'created_at');
print_r($array_data_with_timestamp);
$updated_data = updateTimestampMetadata($array_data_with_timestamp, 'modified_at');
print_r($updated_data);
?>
Add your comment