I'm trying to create a function to return the prime numbers on the ages in a multidimensional array. The problem is the function I created is returning only the first occurence and I want it to return all the occurences.
Here it is what I've done:
function findPrimes(){
$people = [
[
'name' => 'Joseph Richard',
'age' => 23,
'city' => 'Chicago',
'level' => 'Senior',
],
[
'name' => 'John Doe',
'age' => 22,
'city' => 'New York',
'level' => 'Pleno',
],
[
'name' => 'Tess',
'age' => 21,
'city' => 'San Diego',
'level' => 'Junior',
],
[
'name' => 'Steph Morgan',
'age' => 20,
'city' => 'Miami',
'level' => 'Junior',
],
[
'name' => 'Ken Junior Smith',
'age' => 23,
'city' => 'Los Angeles',
'level' => 'Senior',
],
[
'name' => 'Walter Scott',
'age' => 24,
'city' => 'Seattle',
'level' => 'TechLead'
],
[
'name' => 'Diego Maradona',
'age' => 25,
'city' => 'Austin',
'level' => 'TechLead'
],
[
'name' => 'Messi',
'age' => 26,
'city' => 'Portland',
'level' => 'Pleno'
],
[
'name' => 'Hardin Scott',
'age' => 19,
'city' => 'Houston',
'level' => 'Senior'
],
];
$age = array_column($people, 'age');
foreach ($age as $key => $value) {
$isPrime = true;
for($i = 2; $i <= sqrt($value); $i )
{
if($value % $i == 0)
{
$isPrime = false;
}
}
if ($isPrime == true)
{
return "$value is prime number";
}
else {
return "$value is not prime number";
}
}
}
echo findPrimes();
Output: 23
I need it to return all prime numbers in this array. Can anyone help me please?
CodePudding user response:
Your function is executing a return
in the first iteration of the foreach
loop. And returning a string like "x is prime number" seems not to be what you want as result (as you say you want a list of primes).
So define an array $primes
and populate it with those values that are primes, and return that array.
// ... after the initialisation ...
$age = array_column($people, 'age');
$primes = [];
foreach ($age as $key => $value) {
$primes[] = $value; // first assume it is prime
for($i = 2; $i <= sqrt($value); $i ) {
if($value % $i == 0) {
array_pop($primes); // ...then remove it if it's not
break;
}
}
}
return $primes;
}
print_r(findPrimes());
Note that since ages are expected to be in the range of 0 to 140, you can predefine a list of all primes less than 140 (with a sieve). Then all that remains is to check if an age is in that list...
CodePudding user response:
Create an array of prime numbers.
if (in_array($value, $prime_array))
{
return "$value is prime number";
}