Foreach

Hello.

I can’t get it…


array (
  0 => 
  array (
    'name' => 'Aaran Tako',
    'kind' => 'Man,
  ),
  1 => 
  array (
    'name' => 'Abrino Shudu',
    'kind' => 'First Man',
  ),
  2 => 
  array (
    'name' => 'Acrelox',
    'kind' => 'First Man',
  ),
  3 => 
  array (
    'name' => 'Adin Cedra',
    'kind' => 'Man',
  ),
  4 => 
  array (
    'name' => 'Adnanref Adnil',
     'kind' => 'Man',
  ),
  5 => 
  array (
    'name' => 'Agente Foqui',
     'kind' => 'First Man',
  ),

This simple loop won’t find a match for a compound word.
I realy don’t know why.

$map = array(); 

foreach ($peoples as $person) { 

    if ($person['kind'] === 'Man' || $person['kind'] === 'First Man') { 

        $map[] = $person; 

    }
} 

Output gives only matches for “Man”…

Any solutions?

Because === means identical.

You would need something like preg_match or strstr to look at the values.

This will add anything to the stack that contains the word ‘Man’.


<?php
function contains($haystack, $needle, $ignore_case = false){
  return false !== call_user_func_array(
    $ignore_case ? 'stripos' : 'strpos' ,
    array($haystack, $needle)
  );
}

foreach($people as $person){
  if(contains($person['kind'], 'Man')){
    array_push($map, $person);
  }
}


var_dump(
  contains('Kind Man', 'Man')
); # bool(true)

var_dump(
  contains('Kind Man', 'man')
); # bool(false)

var_dump(
  contains('Kind Man', 'man', true)
); # bool(true)

You could also look at array_filter with a custom callback.

Thanks Anthony for sharing part of your wisdom.

The code in the first post works fine, assuming the array is assigned to $peoples and the syntax mistake is fixed. Can you give us some code (for us to copy and paste and try) which shows the problem?

Part of code included by Anthony gave a solution.