Skip to content

Instantly share code, notes, and snippets.

@Gerst20051
Created November 21, 2020 05:02
Show Gist options
  • Save Gerst20051/77e24c4181cfac208161279bc0273500 to your computer and use it in GitHub Desktop.
Save Gerst20051/77e24c4181cfac208161279bc0273500 to your computer and use it in GitHub Desktop.
PHP Age Counting
<?php
// Your goal is to count how many items exist that have an age equal to or greater than 50, and print this final value.
$ch = curl_init('https://coderbyte.com/api/challenges/json/age-counting');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HEADER, 0);
$data = curl_exec($ch);
curl_close($ch);
$json_data = json_decode($data, true);
$items = explode(', ', $json_data['data']);
$count = array_reduce($items, function ($count, $item) {
if (strpos($item, 'age=') !== false) {
$age = explode('=', $item)[1];
if ($age >= 50) return $count + 1;
}
return $count;
}, 0);
print_r($count); // 128
?>
@AtiqurCode
Copy link

I have tried this one to make it simple. But Lol it seems more complex but works as well.
In an interview, I couldn't answer this question answer as well but I think it's a very important and complex problem for newcomers.

<?php

  $ch = curl_init('https://coderbyte.com/api/challenges/json/age-counting');
  curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
  curl_setopt($ch, CURLOPT_HEADER, 0);
  $data = curl_exec($ch);
  curl_close($ch);

  $nedata = json_decode($data, true);

  preg_match_all('/age=(\d+)/', $nedata['data'], $matches);
  $count = 0;
  // $matches[0] contains the full match (e.g., "age=58").
  // $matches[1] = contains only the numbers, which is what you're after.
  foreach($matches[1] as $age)
      if($age >= 50)
          $count++;

  print_r($count);
?>

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment