If i have an array $output that looks like this, how can i search the array and echo out the duration value which in this case is 30. Duration is not always key [18].
Array
(
[16] => hasKeyframes : true
[17] => hasMetadata : true
[18] => duration : 30
[19] => audiosamplerate : 22000
[20] => audiodatarate : 68
[21] => datasize : 1103197
}
Try this function:
function search_value($array, $key, $default_value = false)
{
foreach( $array as $value)
{
list($_key, $_val) = array_map('trim', explode(":", $value) );
if( strtolower($key) == strtolower($_key) )
return $_val;
}
return $default_value;
}
use it like this:
echo search_value( $output, 'duration', 0);
BUT, just like @Lawrence pointed out, it will be MUCH easier if you change your array structure:
$output= array(
'hasKeyframes'=>true,
'hasMetadata'=>true,
'duration'=>'30',
.
.
.
);
This way, you only have to check if key exist and get that value:
echo (!array_key_exists('duration', $output) ? $output['duration'] : 0);
I recommend to sanitize the array at first:
$sanitized = array();
foreach($output as $value) {
$data = explode(':', $value);
$sanitized[trim($data[0])] = trim($data[1]);
}
echo $sanitized['duration'];
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With