How to check if array contains a substring php - php

I have an array of arrays as such below and I want to check if the [avs_id] contains a substring "a_b_c". How to do this in php?
Array
(
[id] => 10003
[avs_id] => a_b_c_3248
)
Array
(
[id] => 10003
[avs_id] => d_e_f_3248
)

You can use array_filter():
$src = 'a_b_c';
$result = array_filter
(
$array,
function( $row ) use( $src )
{
return (strpos( $row['avs_id'], $src ) !== False);
}
);
3v4l.org demo
The result maintain original keys, so you can directly retrieve item(s) matching substring.
If you want only check if substring exists, or the number of items having substring, use this:
$totalMatches = count( $result );

Loop through your array and test for the string in the specific element of your array with strpos as in the example code below.
foreach($yourMainArray as $arrayItem){
if (strpos($arrayItem['avs_id'], 'a_b_c') !== false) {
echo 'true';
}
}

A loop may be more ideal but if you know what array index the string is in that you are after:
$arr = array('id'=>'10003', 'avs_id'=>'a_b_c_3248');
if (strpos($arr['avs_id'], 'a_b_c') !== false) {
echo 'string is in avs_id';
}

You can use :
foreach($yourArray as $arrayItem){
if (strpos($arrayItem['avs_id'], 'a_b_c') !== false) {
//return true : code here
}
}

Related

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

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
}

PHP Check if array element exists in any part of the string

I know how to find if your string equals an array value:
$colors = array("blue","red","white");
$string = "white";
if (!in_array($string, $colors)) {
echo 'not found';
}
...but how do I find if the string CONTAINS any part of the array values?
$colors = array("blue","red","white");
$string = "whitewash"; // I want this to be found in the array
if (!in_array($string, $colors)) {
echo 'not found';
}
Or in one shot:
if( preg_match("(".implode("|",array_map("preg_quote",$colors)).")",$string,$m)) {
echo "Found ".$m[0]."!";
}
This can also be expanded to only allow words that start with an item from your array:
if( preg_match("(\b(?:".implode("|",array_map("preg_quote",$colors))."))",$string,$m)) {
Or case-insensitive:
if( preg_match("(".implode("|",array_map("preg_quote",$colors)).")i",$string,$m)) {
CI with starting only:
if( preg_match("(\b(?:".implode("|",array_map("preg_quote",$colors))."))i",$string,$m)) {
Or anything really ;)
Just loop the array containing the values, and check if they are found in the input string, using strpos
$colors = array("blue","red","white");
$string = "whitewash"; // I want this to be found in the array
foreach ( $colors as $c ) {
if ( strpos ( $string , $c ) !== FALSE ) {
echo "found";
}
}
You can wrap it in a function:
function findString($array, $string) {
foreach ( $array as $a ) {
if ( strpos ( $string , $a ) !== FALSE )
return true;
}
return false;
}
var_dump( findString ( $colors , "whitewash" ) ); // TRUE
Try this working solution
$colors = array("blue", "red", "white");
$string = "whitewash";
foreach ($colors as $color) {
$pos = strpos($string, $color);
if ($pos === false) {
echo "The string '$string' not having substring '$color'.<br>";
} else {
echo "The string '$string' having substring '$color'.<br>";
}
}
There is no built-in function for that, but you could do something like:
$colors = array("blue","red","white");
$string = "whitewash"; // I want this to be found in the array
if (!preg_match('/\Q'.implode('\E|\Q',$colors).'\E/',$string)) {
echo 'not found';
}
This basically makes a regex from your array and matches the string against it. Good method, unless your array is really large.
You would have to iterate over each array element and individually check if it contains it (or a substr of it).
This is similar to what you want to do:
php check if string contains a value in array
$colors = array("blue","red","white");
$string = "whitewash"; // I want this to be found in the array
$hits = array();
foreach($colors as $color) {
if(strpos($string, $color) !== false) {
$hits[] = $color;
}
}
$hits will contain all $colors that have a match in $string.
if(empty($hits)) {
echo 'not found';
}

Php regex returning repeats in nested arrays

I'm trying to get a list of all occurrences of a file being included in a php script.
I'm reading in the entire file, which contains this:
<?php
echo 'Hello there';
include 'some_functions.php';
echo 'Trying to find some includes.';
include 'include_me.php';
echo 'Testtest.';
?>
Then, I run this code on that file:
if (preg_match_all ("/(include.*?;){1}/is", $this->file_contents, $matches))
{
print_r($matches);
}
When I run this match, I get the expected results... which are the two include sections, but I also get repeats of the exact same thing, or random chunks of the include statement. Here is an example of the output:
Array (
[0] => Array ( [0] => include 'some_functions.php'; [1] => include 'include_me.php'; )
[1] => Array ( [0] => include 'some_functions.php'; [1] => include 'include_me.php'; ) )
As you can see, it's nesting arrays with the same result multiple times. I need 1 item in the array for each include statement, no repeats, no nested arrays.
I'm having some trouble with these regular expressions, so some guidance would be nice. Thank you for your time.
what about this one
<?php
preg_match_all( "/include(_once)?\s*\(?\s*(\"|')(.*?)\.php(\"|')\s*\)?\s*;?/i", $this->file_contents, $matches );
// for file names
print_r( $matches[3] );
// for full lines
print_r( $matches[0] );
?>
if you want a better and clean way, then the only way is php's token_get_all
<?php
$tokens = token_get_all( $this->file_contents );
$files = array();
$index = 0;
$found = false;
foreach( $tokens as $token ) {
// in php 5.2+ Line numbers are returned in element 2
$token = ( is_string( $token ) ) ? array( -1, $token, 0 ) : $token;
switch( $token[0] ) {
case T_INCLUDE:
case T_INCLUDE_ONCE:
case T_REQUIRE:
case T_REQUIRE_ONCE:
$found = true;
if ( isset( $token[2] ) ) {
$index = $token[2];
}
$files[$index] = null;
break;
case T_COMMENT:
case T_DOC_COMMENT:
case T_WHITESPACE:
break;
default:
if ( $found && $token[1] === ";" ) {
$found = false;
if ( !isset( $token[2] ) ) {
$index++;
}
}
if ( $found ) {
if ( in_array( $token[1], array( "(", ")" ) ) ) {
continue;
}
if ( $found ) {
$files[$index] .= $token[1];
}
}
break;
}
}
// if your php version is above 5.2
// $files index will be line numbers
print_r( $files );
?>
Use get_included_files(), or the built-in tokenizer if the script is not included
I'm searching through a string of another files contents and not the
current file
Then your best bet is the tokenizer. Try this:
$scriptPath = '/full/path/to/your/script.php';
$tokens = token_get_all(file_get_contents($scriptPath));
$matches = array();
$incMode = null;
foreach($tokens as $token){
// ";" should end include stm.
if($incMode && ($token === ';')){
$matches[] = $incMode;
$incMode = array();
}
// keep track of the code if inside include statement
if($incMode){
$incMode[1] .= is_array($token) ? $token[1] : $token;
continue;
}
if(!is_array($token))
continue;
// start of include stm.
if(in_array($token[0], array(T_INCLUDE, T_INCLUDE_ONCE, T_REQUIRE, T_REQUIRE_ONCE)))
$incMode = array(token_name($token[0]), '');
}
print_r($matches); // array(token name, code)
Please read, how works preg_match_all
First item in array - it return all text, which is in regular expression.
Next items in array - that's texts from regular expression (in parenthesises).
You should use $matches[1]

How to find a value in an array and remove it by using PHP array functions?

How to find if a value exists in an array and then remove it? After removing I need the sequential index order.
Are there any PHP built-in array functions for doing this?
<?php
$my_array = array('sheldon', 'leonard', 'howard', 'penny');
$to_remove = array('howard');
$result = array_diff($my_array, $to_remove);
?>
To search an element in an array, you can use array_search function and to remove an element from an array you can use unset function. Ex:
<?php
$hackers = array ('Alan Kay', 'Peter Norvig', 'Linus Trovalds', 'Larry Page');
print_r($hackers);
// Search
$pos = array_search('Linus Trovalds', $hackers);
// array_seearch returns false if an element is not found
// so we need to do a strict check here to make sure
if ($pos !== false) {
echo 'Linus Trovalds found at: ' . $pos;
// Remove from array
unset($hackers[$pos]);
}
print_r($hackers);
You can refer: https://www.php.net/manual/en/ref.array.php for more array related functions.
You need to find the key of the array first, this can be done using array_search()
Once done, use the unset()
<?php
$array = array( 'apple', 'orange', 'pear' );
unset( $array[array_search( 'orange', $array )] );
?>
Just in case you want to use any of mentioned codes, be aware that array_search returns FALSE when the "needle" is not found in "haystack" and therefore these samples would unset the first (zero-indexed) item. Use this instead:
<?php
$haystack = Array('one', 'two', 'three');
if (($key = array_search('four', $haystack)) !== FALSE) {
unset($haystack[$key]);
}
var_dump($haystack);
The above example will output:
Array
(
[0] => one
[1] => two
[2] => three
)
And that's good!
You can use array_filter to filter out elements of an array based on a callback function. The callback function takes each element of the array as an argument and you simply return false if that element should be removed. This also has the benefit of removing duplicate values since it scans the entire array.
You can use it like this:
$myArray = array('apple', 'orange', 'banana', 'plum', 'banana');
$output = array_filter($myArray, function($value) { return $value !== 'banana'; });
// content of $output after previous line:
// $output = array('apple', 'orange', 'plum');
And if you want to re-index the array, you can pass the result to array_values like this:
$output = array_values($output);
This solution is the combination of #Peter's solution for deleting multiple occurences and #chyno solution for removing first occurence. That's it what I'm using.
/**
* #param array $haystack
* #param mixed $value
* #param bool $only_first
* #return array
*/
function array_remove_values(array $haystack, $needle = null, $only_first = false)
{
if (!is_bool($only_first)) { throw new Exception("The parameter 'only_first' must have type boolean."); }
if (empty($haystack)) { return $haystack; }
if ($only_first) { // remove the first found value
if (($pos = array_search($needle, $haystack)) !== false) {
unset($haystack[$pos]);
}
} else { // remove all occurences of 'needle'
$haystack = array_diff($haystack, array($needle));
}
return $haystack;
}
Also have a look here: PHP array delete by value (not key)
The unset array_search has some pretty terrible side effects because it can accidentally strip the first element off your array regardless of the value:
// bad side effects
$a = [0,1,2,3,4,5];
unset($a[array_search(3, $a)]);
unset($a[array_search(6, $a)]);
$this->log_json($a);
// result: [1,2,4,5]
// what? where is 0?
// it was removed because false is interpreted as 0
// goodness
$b = [0,1,2,3,4,5];
$b = array_diff($b, [3,6]);
$this->log_json($b);
// result: [0,1,2,4,5]
If you know that the value is guaranteed to be in the array, go for it, but I think the array_diff is far safer. (I'm using php7)
$data_arr = array('hello', 'developer', 'laravel' );
// We Have to remove Value "hello" from the array
// Check if the value is exists in the array
if (array_search('hello', $data_arr ) !== false) {
$key = array_search('hello', $data_arr );
unset( $data_arr[$key] );
}
# output:
// It will Return unsorted Indexed array
print( $data_arr )
// To Sort Array index use this
$data_arr = array_values( $data_arr );
// Now the array key is sorted
First of all, as others mentioned, you will be using the "array_search()" & the "unset()" methodsas shown below:-
<?php
$arrayDummy = array( 'aaaa', 'bbbb', 'cccc', 'dddd', 'eeee', 'ffff', 'gggg' );
unset( $arrayDummy[array_search( 'dddd', $arrayDummy )] ); // Index 3 is getting unset here.
print_r( $arrayDummy ); // This will show the indexes as 0, 1, 2, 4, 5, 6.
?>
Now to re-index the same array, without sorting any of the array values, you will need to use the "array_values()" method as shown below:-
<?php
$arrayDummy = array_values( $arrayDummy );
print_r( $arrayDummy ); // Now, you will see the indexes as 0, 1, 2, 3, 4, 5.
?>
Hope it helps.
Okay, this is a bit longer, but does a couple of cool things.
I was trying to filter a list of emails but exclude certain domains and emails.
Script below will...
Remove any records with a certain domain
Remove any email with an exact value.
First you need an array with a list of emails and then you can add certain domains or individual email accounts to exclusion lists.
Then it will output a list of clean records at the end.
//list of domains to exclude
$excluded_domains = array(
"domain1.com",
);
//list of emails to exclude
$excluded_emails = array(
"bob#domain2.com",
"joe#domain3.com",
);
function get_domain($email) {
$domain = explode("#", $email);
$domain = $domain[1];
return $domain;
}
//loop through list of emails
foreach($emails as $email) {
//set false flag
$exclude = false;
//extract the domain from the email
$domain = get_domain($email);
//check if the domain is in the exclude domains list
if(in_array($domain, $excluded_domains)){
$exclude = true;
}
//check if the domain is in the exclude emails list
if(in_array($email, $excluded_emails)){
$exclude = true;
}
//if its not excluded add it to the final array
if($exclude == false) {
$clean_email_list[] = $email;
}
$count = $count + 1;
}
print_r($clean_email_list);
To find and remove multiple instance of value in an array, i have used the below code
$list = array(1,3,4,1,3,1,5,8);
$new_arr=array();
foreach($list as $value){
if($value=='1')
{
continue;
}
else
{
$new_arr[]=$value;
}
}
print_r($new_arr);

Categories