Php search for array element

Search for PHP array element containing string [duplicate]

To find values that match your search criteria, you can use array_filter function:,If you need to find keys of the values that match the criteria, then you need to loop over the array:, Actually, this gives a syntax error, unknown where and it does not work. when I comment this like $matches = array_filter($example, function($var) use ($searchword) < return preg_match("/\b$searchword\b/i", $var); >); the script continues to work, when i add it it breaks. – Lachezar Raychev Nov 8 ’15 at 10:31 , Or even array_keys(preg_grep(‘/\b$searchword\b/i’, $example)). I needed the same functionality and was going to write a wrapper function as well but this is perfect. – MSpreij Sep 19 ’16 at 8:47

To find values that match your search criteria, you can use array_filter function:

$example = array('An example','Another example','Last example'); $searchword = 'last'; $matches = array_filter($example, function($var) use ($searchword) < return preg_match("/\b$searchword\b/i", $var); >); 

If you need to find keys of the values that match the criteria, then you need to loop over the array:

$example = array('An example','Another example','One Example','Last example'); $searchword = 'last'; $matches = array(); foreach($example as $k=>$v) < if(preg_match("/\b$searchword\b/i", $v)) < $matches[$k] = $v; >> 

Answer by Armani Magana

 Output: Array ( [0] => Orange [1] => Apple [2] => Banana [3] => Cherry ) 

Answer by Bonnie Hardin

array_unique — Removes duplicate values from an array, Takes an input array and returns a new array without duplicate values. ,array_count_values() — Counts all the values of an array,Note: Note that array_unique() is not intended to work on multi dimensional arrays.

Array ( [a] => green [0] => red [1] => blue ) 

Answer by Zaylee Weber

To find values that match your search criteria, you can use array_filter function:,is there any predefined function like in_array() that does the job rather than looping through it and compare each values?,Now array $matches contains key-value pairs from the original array where values contain (case- insensitive) word last.,I have an array and I’d like to search for the string ‘green’. So in this case it should return the $arr[2]

I have an array and I’d like to search for the string ‘green’ . So in this case it should return the $arr[2]

$arr = array(0 => 'blue', 1 => 'red', 2 => 'green string', 3 => 'red'); 

Answer by Teagan Noble

39. Write a PHP program to remove duplicate values from an array which contains only strings or only integers.Go to the editor Click me to see the solution,29. Write a PHP program to generate an array with a range taken from a string.Go to the editor Click me to see the solution,44. Write a PHP a function to remove a specified, duplicate entry from an array. Go to the editor Click me to see the solution,31. Write a PHP program to get the index of the highest value in an associative array.Go to the editor Click me to see the solution

Читайте также:  Bytearray to hex string python

11. Write a PHP program to merge (by index) the following two arrays. Go to the editor
Sample arrays :
$array1 = array(array(77, 87), array(23, 45));
$array2 = array(«w3resource», «com»);
Expected Output :

Array ( [0] => Array ( [0] => w3resource [1] => 77 [2] => 87 ) [1] => Array ( [0] => com [1] => 23 [2] => 45 ) ) 

Answer by Jaliyah Ramirez

In the above array, the first duplicate will be found at the index 4 which is the duplicate of the element (2) present at index 1. So, duplicate elements in the above array are 2, 3 and 8.,In this program, we need to print the duplicate elements present in the array. This can be done through two loops. The first loop will select an element and the second loop will iteration through the array by comparing the selected element with other elements. If a match is found, print the duplicate element.,Duplicate elements can be found using two loops. The outer loop will iterate through the array from 0 to length of the array. The outer loop will select an element. The inner loop will be used to compare the selected element with the rest of the elements of the array.,JavaTpoint offers college campus training on Core Java, Advance Java, .Net, Android, Hadoop, PHP, Web Technology and Python. Please mail your requirement at [email protected] Duration: 1 week to 2 week

Duplicate elements in given array: 2 3 8 

Источник

Note:

If needle is a string, the comparison is done in a case-sensitive manner.

If the third parameter strict is set to true then the array_search() function will search for identical elements in the haystack . This means it will also perform a strict type comparison of the needle in the haystack , and objects must be the same instance.

Return Values

Returns the key for needle if it is found in the array, false otherwise.

If needle is found in haystack more than once, the first matching key is returned. To return the keys for all matching values, use array_keys() with the optional search_value parameter instead.

This function may return Boolean false , but may also return a non-Boolean value which evaluates to false . Please read the section on Booleans for more information. Use the === operator for testing the return value of this function.

Examples

Example #1 array_search() example

$array = array( 0 => ‘blue’ , 1 => ‘red’ , 2 => ‘green’ , 3 => ‘red’ );

$key = array_search ( ‘green’ , $array ); // $key = 2;
$key = array_search ( ‘red’ , $array ); // $key = 1;
?>

See Also

  • array_keys() — Return all the keys or a subset of the keys of an array
  • array_values() — Return all the values of an array
  • array_key_exists() — Checks if the given key or index exists in the array
  • in_array() — Checks if a value exists in an array

User Contributed Notes 16 notes

About searcing in multi-dimentional arrays; two notes on «xfoxawy at gmail dot com»;

It perfectly searches through multi-dimentional arrays combined with array_column() (min php 5.5.0) but it may not return the values you’d expect.

Since array_column() will produce a resulting array; it won’t preserve your multi-dimentional array’s keys. So if you check against your keys, it will fail.

$people = array(
2 => array(
‘name’ => ‘John’ ,
‘fav_color’ => ‘green’
),
5 => array(
‘name’ => ‘Samuel’ ,
‘fav_color’ => ‘blue’
)
);

Читайте также:  Java util timer methods

$found_key = array_search ( ‘blue’ , array_column ( $people , ‘fav_color’ ));
?>

Here, you could expect that the $found_key would be «5» but it’s NOT. It will be 1. Since it’s the second element of the produced array by the array_column() function.

Secondly, if your array is big, I would recommend you to first assign a new variable so that it wouldn’t call array_column() for each element it searches. For a better performance, you could do;

$colors = array_column ( $people , ‘fav_color’ );
$found_key = array_search ( ‘blue’ , $colors );
?>

If you are using the result of array_search in a condition statement, make sure you use the === operator instead of == to test whether or not it found a match. Otherwise, searching through an array with numeric indicies will result in index 0 always getting evaluated as false/null. This nuance cost me a lot of time and sanity, so I hope this helps someone. In case you don’t know what I’m talking about, here’s an example:

$code = array( «a» , «b» , «a» , «c» , «a» , «b» , «b» ); // infamous abacabb mortal kombat code 😛

// this is WRONG
while (( $key = array_search ( «a» , $code )) != NULL )
<
// infinite loop, regardless of the unset
unset( $code [ $key ]);
>

// this is _RIGHT_
while (( $key = array_search ( «a» , $code )) !== NULL )
<
// loop will terminate
unset( $code [ $key ]);
>
?>

for searching case insensitive better this:

array_search ( strtolower ( $element ), array_map ( ‘strtolower’ , $array ));
?>

var_dump ( array_search ( ‘needle’ , [ 0 => 0 ])); // int(0) (!)

var_dump ( array_search ( ‘needle’ , [ 0 => 0 ], true )); // bool(false)

var_dump ( array_search ( ‘needle’ , [ 0 => 0 ])); // bool(false)

Despite PHP’s amazing assortment of array functions and juggling maneuvers, I found myself needing a way to get the FULL array key mapping to a specific value. This function does that, and returns an array of the appropriate keys to get to said (first) value occurrence.

function array_recursive_search_key_map($needle, $haystack) foreach($haystack as $first_level_key=>$value) if ($needle === $value) return array($first_level_key);
> elseif (is_array($value)) $callback = array_recursive_search_key_map($needle, $value);
if ($callback) return array_merge(array($first_level_key), $callback);
>
>
>
return false;
>

$nested_array = $sample_array = array(
‘a’ => array(
‘one’ => array (‘aaa’ => ‘apple’, ‘bbb’ => ‘berry’, ‘ccc’ => ‘cantalope’),
‘two’ => array (‘ddd’ => ‘dog’, ‘eee’ => ‘elephant’, ‘fff’ => ‘fox’)
),
‘b’ => array(
‘three’ => array (‘ggg’ => ‘glad’, ‘hhh’ => ‘happy’, ‘iii’ => ‘insane’),
‘four’ => array (‘jjj’ => ‘jim’, ‘kkk’ => ‘kim’, ‘lll’ => ‘liam’)
),
‘c’ => array(
‘five’ => array (‘mmm’ => ‘mow’, ‘nnn’ => ‘no’, ‘ooo’ => ‘ohh’),
‘six’ => array (‘ppp’ => ‘pidgeon’, ‘qqq’ => ‘quail’, ‘rrr’ => ‘rooster’)
)
);

$array_keymap = array_recursive_search_key_map($search_value, $nested_array);

But again, with the above solution, PHP again falls short on how to dynamically access a specific element’s value within the nested array. For that, I wrote a 2nd function to pull the value that was mapped above.

function array_get_nested_value($keymap, $array)
$nest_depth = sizeof($keymap);
$value = $array;
for ($i = 0; $i < $nest_depth; $i++) $value = $value[$keymap[$i]];
>

usage example:
——————-
echo array_get_nested_value($array_keymap, $nested_array); // insane

Источник

Checking if an Element exists in a PHP Array

To check if an element exists in a PHP array, you can use the in_array($search, $array, $mode) function. The $search parameter specifies the element or value to search in the specified array and can be of a mixed type (string, integer, or other types). If the parameter is a string type, the search will be case-sensitive. The $array parameter specifies the array to search for the value. The $mode parameter is an optional boolean parameter that specifies the search mode. If the parameter is set to TRUE, then the in_array() function will search for a value with the same value type as specified in the «search» parameter. The default value for the «mode» parameter is FALSE. In this PHP Search In Array example, we use the in_array() function to check whether the given value exists in the array. Click Execute to run the PHP In Array Example online and see the result.

Читайте также:  Css отступ слева от блока

What is PHP?

PHP is a general-purpose server-side language for web development. PHP supports many protocols and standards, such as HTTP, SMTP, POP3, IMAP, FTP, and XML. PHP integrates with other web development technologies such as HTML, CSS, JavaScript, and SQL. Due to its open nature and huge developer community, PHP has many libraries and frameworks that simplify and speed up web application development. PHP is also a cross-platform language, allowing it to run on various operating systems such as Windows, macOS, Linux, and Unix.

What is an array in PHP?

An array in PHP is a variable we use to store data containing various elements. The elements of an array are identified by a unique key or index, which can be a number or a string. PHP has two types of arrays: indexed arrays and associative arrays. PHP provides many built-in functions for working with arrays, including searching, sorting, splitting a string to array, converting an array to string, converting an array to JSON, and getting the length of an array.

PHP In Array Syntax

in_array(search, array, mode)
  • search: specifies the element or value to look up in the given array
  • array: specifying an array to search for a value
  • mode (optional): specifies the mode to perform the search. If set to «TRUE», the in_array() function searches for the search-string and specific type in the array. The default value for this parameter is «FALSE».

PHP In Array Examples

The following are examples of checking if an element exists in a PHP array:

Checking if a element exists in an associative array

The following is an example of checking if a value exists in an associative array:

 "Leo", "age" => 26, "city" => "Barcelona" ); if (in_array("Leo", $arr)) < echo "Found"; >else < echo "Not found"; >?> #output: Found
Checking if an element exists in a multidimensional array

The following is an example of checking if a value exists in a multidimensional array:

 "Leo", "age" => 26), array("name" => "Alice", "age" => 32), array("name" => "Jack", "age" => 27) ); if (in_array("Alice", array_column($arr, "name"))) < echo "Found"; >else < echo "Not found"; >?> #output: Found
Checking if an element exists in an array, case-insensitive

To check if an array contains an element, case insensitively, you can convert all elements in the array and the target element to lowercase (or uppercase) and then use the in_array() method to check for the presence of the target element:

See also

Источник

Оцените статью