Skip to content

Instantly share code, notes, and snippets.

@mistic100
Last active January 2, 2016 20:29
Show Gist options
  • Select an option

  • Save mistic100/8357035 to your computer and use it in GitHub Desktop.

Select an option

Save mistic100/8357035 to your computer and use it in GitHub Desktop.
[PHP] Search a string in array values
<?php
/**
* Search a string in array values
*
* @param string $needle
* @param array $haystack
* @param bool $match_all - return all instances
* @param bool $preg_mode - search in PCRE mode
* @return mixed|array
*/
function array_pos($needle, $haystack, $match_all=false, $preg_mode=false)
{
if ($match_all) $matches = array();
foreach ($haystack as $i => $row)
{
if (!is_array($row))
{
if (!$preg_mode)
{
if (strpos($row, $needle) !== false)
{
if (!$match_all) return $i;
else array_push($matches, $i);
}
}
else
{
if (preg_match($needle, $row) === 1)
{
if (!$match_all) return $i;
else array_push($matches, $i);
}
}
}
}
if (!$match_all or !count($matches)) return false;
return $matches;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment