Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

php search array which contains "key : value" items

Tags:

arrays

php

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
}
like image 812
Pinkie Avatar asked Aug 03 '26 18:08

Pinkie


2 Answers

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);
like image 197
ariefbayu Avatar answered Aug 06 '26 11:08

ariefbayu


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'];
like image 38
cem Avatar answered Aug 06 '26 10:08

cem



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!