check if string exists in array element - php

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

Related

PHP in_array not working with current array structure

I am using a custom method to return a query as an array.
This is being used to check if a discount code posted is in the DB.
The array ends up as example:
Array
(
[0] => stdClass Object
(
[code] => SS2015
)
[1] => stdClass Object
(
[code] => SS2016
)
)
So when I am trying to do:
if ( ! in_array($discount_code, $valid_codes)) {
}
Its not working. Is there a way I can still use the function for query to array I am using and check if its in the array?
No issues, I can make a plain array of the codes but just wanted to keep things consistent.
Read about json_encode (serialize data to json) and json_decode (return associative array from serialized json, if secondary param is true). Also array_column gets values by field name. so we have array of values in 1 dimensional array, then let's check with in_array.
function isInCodes($code, $codes) {
$codes = json_encode($codes); // serialize array of objects to json
$codes = json_decode($codes, true); // unserialize json to associative array
$codes = array_column($codes, 'code'); // build 1 dimensional array of code fields
return in_array($code, $codes); // check if exists
}
if(!isInCodes($discount_code, $valid_codes)) {
// do something
}
Use array_filter() to identify the objects having property code equal with $discount_code:
$in_array = array_filter(
$valid_codes,
function ($item) use ($discount_code) {
return $item->code == $discount_code;
}
);
if (! count($in_array)) {
// $discount_code is not in $valid_codes
}
If you need to do the same check many times, in different files, you can convert the above code snippet to a function:
function code_in_array($code, array $array)
{
return count(
array_filter(
$array,
function ($item) use ($code) {
return $item->code == $code;
}
)
) != 0;
}
if (! code_in_array($discount_code, $valid_codes)) {
// ...
}
try this
function in_array_r($needle, $haystack, $strict = false) {
foreach ($haystack as $item) {
if (($strict ? $item === $needle : $item == $needle) || (is_array($item) && in_array_r($needle, $item, $strict))) {
return true;
}
}
return false;
}
then
echo in_array_r("SS2015", $array) ? 'found' : 'not found';
why not solve it as a school task - fast and easy:
for($i = 0; $i < count($valid_codes); $i++) if ($valid_codes[$]->code == $discount_code) break;
if ( ! ($i < count($valid_codes))) { // not in array
}

search a php array for partial string match [duplicate]

This question already has answers here:
Filter multidimensional array based on partial match of search value
(3 answers)
Native function to filter array by prefix
(6 answers)
Closed 1 year ago.
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');
is there any predefined function like in_array() that does the job rather than looping through it and compare each values?
For a partial match you can iterate the array and use a string search function like strpos().
function array_search_partial($arr, $keyword) {
foreach($arr as $index => $string) {
if (strpos($string, $keyword) !== FALSE)
return $index;
}
}
For an exact match, use in_array()
in_array('green', $arr)
You can use preg_grep function of php. It's supported in PHP >= 4.0.5.
$array = array(0 => 'blue', 1 => 'red', 2 => 'green string', 3 => 'red');
$m_array = preg_grep('/^green\s.*/', $array);
$m_array contains matched elements of array.
There are several ways...
$arr = array(0 => 'blue', 1 => 'red', 2 => 'green string', 3 => 'red');
Search the array with a loop:
$results = array();
foreach ($arr as $value) {
if (strpos($value, 'green') !== false) { $results[] = $value; }
}
if( empty($results) ) { echo 'No matches found.'; }
else { echo "'green' was found in: " . implode('; ', $results); }
Use array_filter():
$results = array_filter($arr, function($value) {
return strpos($value, 'green') !== false;
});
In order to use Closures with other arguments there is the use-keyword. So you can abstract it and wrap it into a function:
function find_string_in_array ($arr, $string) {
return array_filter($arr, function($value) use ($string) {
return strpos($value, $string) !== false;
});
}
$results = find_string_in_array ($arr, 'green');
if( empty($results) ) { echo 'No matches found.'; }
else { echo "'green' was found in: " . implode('; ', $results); }
Here's a working example: http://codepad.viper-7.com/xZtnN7
PHP 5.3+
array_walk($arr, function($item, $key) {
if(strpos($item, 'green') !== false) {
echo 'Found in: ' . $item . ', with key: ' . $key;
}
});
for search with like as sql with '%needle%' you can try with
$input = preg_quote('gree', '~'); // don't forget to quote input string!
$data = array(
1 => 'orange',
2 => 'green string',
3 => 'green',
4 => 'red',
5 => 'black'
);
$result = preg_filter('~' . $input . '~', null, $data);
and result is
{
"2": " string",
"3": ""
}
function check($string)
{
foreach($arr as $a) {
if(strpos($a,$string) !== false) {
return true;
}
}
return false;
}
A quick search for a phrase in the entire array might be something like this:
if (preg_match("/search/is", var_export($arr, true))) {
// match
}
function findStr($arr, $str)
{
foreach ($arr as &$s)
{
if(strpos($s, $str) !== false)
return $s;
}
return "";
}
You can change the return value to the corresponding index number with a little modification if you want, but since you said "...return the $arr[2]" I wrote it to return the value instead.
In order to find out if UTF-8 case-insensitive substring is present in array, I found that this method would be much faster than using mb_strtolower or mb_convert_case:
Implode the array into a string: $imploded=implode(" ", $myarray);.
Convert imploded string to lowercase using custom function:
$lowercased_imploded = to_lower_case($imploded);
function to_lower_case($str)
{
$from_array=["A","B","C","D","E","F","G","H","I","J","K","L","M","N","O","P","Q","R","S","T","U","V","W","X","Y","Z","Ä","Ö","Ü","Õ","Ž","Š"];
$to_array=["a","b","c","d","e","f","g","h","i","j","k","l","m","n","o","p","q","r","s","t","u","v","w","x","y","z","ä","ö","ü","õ","ž","š"];
foreach($from_array as $key=>$val){$str=str_replace($val, $to_array[$key], $str);}
return $str;
}
Search for match using ordinary strpos: if(strpos($lowercased_imploded, "substring_to_find")!==false){do something}
This is a function for normal or multidimensional arrays.
Case in-sensitive
Works for normal arrays and multidimentional
Works when finding full or partial stings
Here's the code (version 1):
function array_find($needle, array $haystack, $column = null) {
if(is_array($haystack[0]) === true) { // check for multidimentional array
foreach (array_column($haystack, $column) as $key => $value) {
if (strpos(strtolower($value), strtolower($needle)) !== false) {
return $key;
}
}
} else {
foreach ($haystack as $key => $value) { // for normal array
if (strpos(strtolower($value), strtolower($needle)) !== false) {
return $key;
}
}
}
return false;
}
Here is an example:
$multiArray = array(
0 => array(
'name' => 'kevin',
'hobbies' => 'Football / Cricket'),
1 => array(
'name' => 'tom',
'hobbies' => 'tennis'),
2 => array(
'name' => 'alex',
'hobbies' => 'Golf, Softball')
);
$singleArray = array(
0 => 'Tennis',
1 => 'Cricket',
);
echo "key is - ". array_find('cricket', $singleArray); // returns - key is - 1
echo "key is - ". array_find('cricket', $multiArray, 'hobbies'); // returns - key is - 0
For multidimensional arrays only - $column relates to the name of the key inside each array.
If the $needle appeared more than once, I suggest adding onto this to add each key to an array.
Here is an example if you are expecting multiple matches (version 2):
function array_find($needle, array $haystack, $column = null) {
$keyArray = array();
if(is_array($haystack[0]) === true) { // for multidimentional array
foreach (array_column($haystack, $column) as $key => $value) {
if (strpos(strtolower($value), strtolower($needle)) !== false) {
$keyArray[] = $key;
}
}
} else {
foreach ($haystack as $key => $value) { // for normal array
if (strpos(strtolower($value), strtolower($needle)) !== false) {
$keyArray[] = $key;
}
}
}
if(empty($keyArray)) {
return false;
}
if(count($keyArray) == 1) {
return $keyArray[0];
} else {
return $keyArray;
}
}
This returns the key if it has just one match, but if there are multiple matches for the $needle inside any of the $column's then it will return an array of the matching keys.
Hope this helps :)

Find with like condition in array

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.

Search number in array

$record_record contains:
Array
(
[0] => Array
(
[id] => 252
[origin] => laptop.me.
)
[1] => Array
(
[id] => 255
[origin] => hello.me.
)
[2] => Array
(
[id] => 254
[origin] => intel.me.
)
)
I need to search if 255 is exist in the array. The code below didn't work.
if (in_array('255', $record_record, true)) {
echo "'255' found with strict check\n";
}
else {
echo "nope\n";
}
I had a feeling because it's a nested array the function will not work. Help me please?
You need to do something like this:
<?php
function id_exists ($array, $id, $strict = FALSE) {
// Loop outer array
foreach ($array as $inner) {
// Make sure id is set, and compare it to the search value
if (isset($inner['id']) && (($strict) ? $inner['id'] === $id : $inner['id'] == $id)) {
// We found it
return TRUE;
}
}
// We didn't find it
return FALSE;
}
if (id_exists($record_record, 255, true)) {
echo "'255' found with strict check\n";
} else {
echo "nope\n";
}
Do something like :
foreach($record_record as $sub_array){
if (in_array('255', $sub_array, true)) {
echo "'255' found with strict check\n";
}
else {
echo "nope\n";
}
}
You'll need a recursive function for that. From elusive:
function in_array_r($needle, $haystack, $strict = true) {
foreach ($haystack as $item) {
if (($strict ? $item === $needle : $item == $needle) || (is_array($item) && in_array_r($needle, $item, $strict))) {
return true;
}
}
return false;
}
Or, if your array structure will never change, just write a simple loop:
function in_2dimensional_array($needle, $haystack, $strict = true){
foreach ($haystack as $item) {
if (in_array($needle, $haystack, true)) {
return true;
}
}
return false;
}
Hacky solution. Someone else will post a nice one using array_map or something similar.
function in_nested_array($val, $arr)
{
$matched = false;
foreach ($arr AS $ar)
{
if (in_array($val, $ar, true)
{
$matched = true;
break;
}
}
return $matched;
}
if (in_nested_array(255, $record_record))
{
// partay
}
<?php
foreach($record_record as $record) {
$key = array_search('255', $record);
if ($key) {
echo "'255' found with strict check\n";
}
}
?>

best way to check a empty array?

How can I check an array recursively for empty content like this example:
Array
(
[product_data] => Array
(
[0] => Array
(
[title] =>
[description] =>
[price] =>
)
)
[product_data] => Array
(
[1] => Array
(
[title] =>
[description] =>
[price] =>
)
)
)
The array is not empty but there is no content. How can I check this with a simple function?
Thank!!
function is_array_empty($InputVariable)
{
$Result = true;
if (is_array($InputVariable) && count($InputVariable) > 0)
{
foreach ($InputVariable as $Value)
{
$Result = $Result && is_array_empty($Value);
}
}
else
{
$Result = empty($InputVariable);
}
return $Result;
}
If your array is only one level deep you can also do:
if (strlen(implode('', $array)) == 0)
Works in most cases :)
Solution with array_walk_recursive:
function empty_recursive($value)
{
if (is_array($value)) {
$empty = TRUE;
array_walk_recursive($value, function($item) use (&$empty) {
$empty = $empty && empty($item);
});
} else {
$empty = empty($value);
}
return $empty;
}
Assuming the array will always contain the same type of data:
function TestNotEmpty($arr) {
foreach($arr as $item)
if(isset($item->title) || isset($item->descrtiption || isset($item->price))
return true;
return false;
}
Short circuiting included.
function hasValues($input, $deepCheck = true) {
foreach($input as $value) {
if(is_array($value) && $deepCheck) {
if($this->hasValues($value, $deepCheck))
return true;
}
elseif(!empty($value) && !is_array($value))
return true;
}
return false;
}
Here's my version. Once it finds a non-empty string in an array, it stops. Plus it properly checks on empty strings, so that a 0 (zero) is not considered an empty string (which would be if you used empty() function). By the way even using this function just for strings has proven invaluable over the years.
function isEmpty($stringOrArray) {
if(is_array($stringOrArray)) {
foreach($stringOrArray as $value) {
if(!isEmpty($value)) {
return false;
}
}
return true;
}
return !strlen($stringOrArray); // this properly checks on empty string ('')
}
If anyone stumbles on this question and needs to check if the entire array is NULL, meaning that each pair in the array is equal to null, this is a handy function. You could very easily modify it to return true if any variable returns NULL as well. I needed this for a certain web form where it updated users data and it was possible for it to come through completely blank, therefor not needing to do any SQL.
$test_ary = array("1"=>NULL, "2"=>NULL, "3"=>NULL);
function array_empty($ary, $full_null=false){
$null_count = 0;
$ary_count = count($ary);
foreach($ary as $value){
if($value == NULL){
$null_count++;
}
}
if($full_null == true){
if($null_count == $ary_count){
return true;
}else{
return false;
}
}else{
if($null_count > 0){
return true;
}else{
return false;
}
}
}
$test = array_empty($test_ary, $full_null=true);
echo $test;
$arr=array_unique(array_values($args));
if(empty($arr[0]) && count($arr)==1){
echo "empty array";
}
Returns TRUE if passed a variable other than an array, or if any of the nested arrays contains a value (including falsy values!). Returns FALSE otherwise.
Short circuits.
function has_values($var) {
if (is_array($var)) {
if (empty($var)) return FALSE;
foreach ($var as $val) {
if(has_values($val)) return TRUE;
}
return FALSE;
}
return TRUE;
}
Here's a good utility function that will return true (1) if the array is empty, or false (0) if not:
function is_array_empty( $mixed ) {
if ( is_array($mixed) ) {
foreach ($mixed as $value) {
if ( ! is_array_empty($value) ) {
return false;
}
}
} elseif ( ! empty($mixed) ) {
return false;
}
return true;
}
For example, given a multidimensional array:
$products = array(
'product_data' => array(
0 => array(
'title' => '',
'description' => null,
'price' => '',
),
),
);
You'll get a true value returned from is_array_empty(), since there are no values set:
var_dump( is_array_empty($products) );
View this code interactively at: http://codepad.org/l2C0Efab
I needed a function to filter an array recursively for non empty values.
Here is my recursive function:
function filterArray(array $array, bool $keepNonArrayValues = false): array {
$result = [];
foreach ($array as $key => $value) {
if (is_array($value)) {
$value = $this->filterArray($value, $keepNonArrayValues);
}
// keep non empty values anyway
// otherwise only if it is not an array and flag $keepNonArrayValues is TRUE
if (!empty($value) || (!is_array($value) && $keepNonArrayValues)) {
$result[$key] = $value;
}
}
return array_slice($result, 0)
}
With parameter $keepNonArrayValues you can decide if values such 0 (number zero), '' (empty string) or false (bool FALSE) shout be kept in the array. In other words: if $keepNonArrayValues = true only empty arrays will be removed from target array.
array_slice($result, 0) has the effect that numeric indices will be rearranged (0..length-1).
Additionally, after filtering the array by this function it can be tested with empty($filterredArray).

Categories