Find with like condition in array - php

I am having following array and I want to use search and sort.Search and sort are like sorting which we do with MySQL "LIKE" condition but in array not in database.
Array
(
[4] => Varun Kumar
[14] => Jason Ince
)
Like on typing 'jas' record with Jason Ince must come out of it with keys and values and rest of the record respectively.

Do you mean something like:
foreach($yourArr as $key => $value) {
if (strpos($value, $yourString) !== false) {
//results here
}
}

You can use array_filter:
$filtered_array = array_filter($original_array, create_function($a, 'return stristr($a,"jas")!==false'));
OR, if you're using php 5.3+, syntax is:
$filtered_array = array_filter($original_array, function($a){ return stristr($a,"jas")!==false });

function arraySearch( $array, $search ) {
foreach ($array as $a ) {
if(strstr( $a, $search)){
echo $a;
}
}
return false;
}
arraySearch(array("php","mysql","search"),"my"); // will return mysql

You could also use this way:
function check($yourString)
{
foreach($yourArr as $key => $value) {
if (strpos($value, $yourString) !== false)
return strpos($value, $yourString);
}
}
So that you can check the condition if not false.

Related

How to fetch value and key from an array which contain specific letter using php

I need to find the key and the value from an array that contains a specific letter without using the loop.
for Eg
$animal= array('lion','elephant','tiger');
I need to fetch the key and value which contain 'io'
output :
0 - lion
You can use array_filter with option ARRAY_FILTER_USE_BOTH
$animal = array('lion','elephant','tiger');
$search = 'io';
$res = array_filter($animal, function($v, $k) use($search){
return strpos($v, $search);
}, ARRAY_FILTER_USE_BOTH);
echo '<pre>';
print_r($res);
Working example :- https://3v4l.org/bdDSF
loop over array with foreach and use a test strpos($value, $search) !== false, Which means $search exist in $value, So take position of it which is $key with its value, store them in $array. or just show them immediately (uncomment the echo line).
$animal = array('lion','elephant','tiger','ions');
$array = [];
$search = 'io';
foreach ($animal as $key => $value) {
if(strpos($value, $search) !== false){
$array[$key] = $value;
//echo $key." - ".$value."<br>";
}
}
Results:
foreach ($array as $key => $value) {
echo $key." - ".$value."<br>";
}
Output:
/*
0 - lion
3 - ions
*/
use array_walk function. this function will apply user-defined callback function to each element of the array
$animal= ['lion','elephant','tiger','lions'];
array_walk($animal, function($value, $key) use (&$array)
{
if(strpos($value,'io') !== false)
$array[$key]= $value;
});
var_dump($array);
it give output:
Array (
[0] => lion
[3] => lions )

check if string exists in array element

Is there any function that can do what strpos does, but on the elements of an array ? for example I have this array :
Array
(
[0] => a66,b30
[1] => b30
)
each element of the array can contain a set of strings, separated by commas.
Let's say i'm looking for b30.
I want that function to browse the array and return 0 and 1. can you help please ? the function has to do the oppsite of what this function does.
Try this (not tested) :
function arraySearch($array, $search) {
if(!is_array($array)) {
return 0;
}
if(is_array($search) || is_object($search)) {
return 0;
}
foreach($array as $k => $v) {
if(is_array($v) || is_object($v)) {
continue;
}
if(strpos($v, $search) !== false) {
return 1;
}
}
return 0;
}
You could also use preg_grep for this.
<?php
$a = array(
'j98',
'a66,b30',
'b30',
'something',
'a40'
);
print_r( count(preg_grep('/(^|,)(b30)(,|$)/', $a)) ? 1 : 0 );
https://eval.in/412598

In Array with regex

I`m using $_POST array with results of checkbox's selected from a form.
I'm thinking of using php in_array function but how could I extract only values that start with chk Given the following array:
Array (
[chk0] => 23934567622639616
[chk3] => 23934567622639618
[chk4] => 23934567622639619
[select-all] => on
[process] => Process
)
Thanks!
Simple and fast
$result=array();
foreach($_POST as $key => $value){
if(substr($key, 0, 2) == 'chk'){
$result[$key] = $value;
}
}
Lots of ways to do this, I like array_filter.
Example:
$result = array_filter(
$_POST,
function ($key) {
return strpos($key, "chk") === 0;
},
ARRAY_FILTER_USE_KEY
);
Here's a solution from http://php.net/manual/en/function.preg-grep.php
<?php
function preg_grep_keys($pattern, $input, $flags = 0) {
return array_intersect_key($input, array_flip(preg_grep($pattern, array_keys($input), $flags)));
}
?>
I would use array_filter
$ary = array_filter($originalArray,
function($key){ return preg_match('/chk/', $key); },
ARRAY_FILTER_USE_KEY
);

PHP: search array with similar matching keywords

I have an array like
$arr = array(0 => array(id=>1,name=>"Apple"),
1 => array(id=>2,name=>"Orange"),
2 => array(id=>3,name=>"Grape")
);
I have written the code for searching the multidimensional array.
Here is it
function search($array, $key, $value)
{
$results = array();
search_r($array, $key, $value, $results);
return $results;
}
function search_r($array, $key, $value, &$results)
{
if (!is_array($array)) {
return;
}
if (isset($array[$key]) && $array[$key] == $value) {
$results[] = $array;
}
foreach ($array as $subarray) {
search_r($subarray, $key, $value, $results);
}
}
But it works only for exactly matching keywords.
What I need is, If I search for 'Gra' in this array. The function should return
array(0 => array(id=>1,name=>"Grape")
);
This seems to be something like mysql %LIKE% condition.How can this be done in PHP arrays ?
When checking if the string matches you can instead use strpos
strpos($strToCheck, 'Gra') !== false;//Will match if $strToCheck contains 'Gra'
strpos($strToCheck, 'Gra') === 0; //Will match if $strToCheck starts with 'Gra'
Note that the above is case sensitive. For case insensitivity you can strtoupper both strings before comparing use strripos instead.
In your example the check would become:
if (isset($array[$key]) && strpos($array[$key],$value) !== false) {
$results[] = $array;
}
You can use stristr function for string manipulations in php, and you'll don't have to think about different cases and cast them to uppercase.
stristr function is not case sensitive, so your code will like this
if (isset($array[$key]) && stristr($array[$key], $value) !== false) {
$results[] = $array;
}
Focussing on the line here that you wrote -
if (isset($array[$key]) && $array[$key] == $value) {
We can modify it to search for substrings, rather than exact match -
if (isset($array[$key]) && strpos($array[$key], $value)) {
This will try to find if the value is present somewhere in the content of $array[$key]
Hope it helps

Selecting an element in an Associative Array in a different way in PHP

Ok I have this kind of associative array in PHP
$arr = array(
"fruit_aac" => "apple",
"fruit_2de" => "banana",
"fruit_ade" => "grapes",
"other_add" => "sugar",
"other_nut" => "coconut",
);
now what I want is to select only the elements that starts with key fruit_. How can be this possible? can I use a regex? or any PHP array functions available? Is there any workaround? Please give some examples for your solutions
$fruits = array();
foreach ($arr as $key => $value) {
if (strpos($key, 'fruit_') === 0) {
$fruits[$key] = $value;
}
}
One solution is as follows:
foreach($arr as $key => $value){
if(strpos($key, "fruit_") === 0) {
...
...
}
}
The === ensures that the string was found at position 0, since strpos can also return FALSE if string was not found.
You try it:
function filter($var) {
return strpos($var, 'fruit_') !== false;
}
$arr = array(
"fruit_aac"=>"apple",
"fruit_2de"=>"banana",
"fruit_ade"=>"grapes",
"other_add"=>"sugar",
"other_nut"=>"coconut",
);
print_r(array_flip(array_filter(array_flip($arr), 'filter')));
If you want to try regular expression then you can try code given below...
$arr = array("fruit_aac"=>"apple",
"fruit_2de"=>"banana",
"fruit_ade"=>"grapes",
"other_add"=>"sugar",
"other_nut"=>"coconut",
);
$arr2 = array();
foreach($arr AS $index=>$array){
if(preg_match("/^fruit_.*/", $index)){
$arr2[$index] = $array;
}
}
print_r($arr2);
I hope it will be helpful for you.
thanks

Categories