- Php check if element is in array
- Check if element is in array, but exclude array’s last element?
- Check if value is in array
- Check the element in the array and if it doesn’t exist out data into database
- Check if elements are in a array and increment
- in_array
- Parameters
- Return Values
- Examples
- See Also
- User Contributed Notes 8 notes
- Check if an Array contains a value in PHP
- Method 1: Using in_array() function
- Frequently Asked:
- Method 2: Using array_search() function
- Summary
- Related posts:
- Share your love
- Leave a Comment Cancel Reply
- Terms of Use
- Disclaimer
Php check if element is in array
Obscenity Filters: Bad Idea, or Incredibly Intercoursing Bad Idea? Solution 2: This will match a bad word on its own only. They’ll use similar sounding characters or special characters as both substitutions and additions.
Check if element is in array, but exclude array’s last element?
Use array_slice() to slice the array and use it. The below code doesn’t include the last element in the array.
$fkTableName = $fkTableArr[$colNr0]; if (!in_array($fkTableName, array_slice($fkTableArr, -1))) // do sth
If you want to not affect the array, try this:
if (in_array($fkTableName, $fkTableArr) && $fkTableName != end($fkTableArr)) < // element in array, but not last item >
Php — Check if an object exists in an array, The answer suggests to put the first set of objects in an array and use the id as key. When the second set of objects is processed, use the object id to find the object with the same id in the array. By using the id as key (and not a numeric key generated automatically), the object can be identified without scanning the … Code sampleif (isset($array1[$object->id]))/> else/> Feedback
Check if value is in array
Technically there are a few options, and some other answers point these out. Realistically, however, I would say do not do this.
Profanity filters are notoriously frustrating and limiting for users with unusual or foreign names/address/etc.
Please see: http://en.wikipedia.org/wiki/Swear_filter#Unintended_consequences
Additionally, if your users want to find a way around the filter, they will. They’ll use similar sounding characters or special characters as both substitutions and additions.
EDIT: There is an excellent stackoverflow question already addressing this issue. please see How do you implement a good profanity filter?
EDIT: although the above stackoverflow question refers to Jeff’s post about this, it can’t hurt to repeat and reinforce. Obscenity Filters: Bad Idea, or Incredibly Intercoursing Bad Idea?
$name = $_POST['Name']; foreach($profanities as $profanity) < if (preg_match('/\w' . preg_quote($profanity, '/') . '\w/i', $name) < // Bad word on its own >>
This will match a bad word on its own only. i.e. it will match bad in Is it bad? but not in baddy . You can remove the word boundaries if you want to match that, or perhaps try strstr() .
However, a valid name may contain a substring that is considered bad if you decide to check for simple string matching.
What if I wanted to name my username after my hometown?
This code will match all bad words found by searching a case-insensative match.
foreach($profanities as $profanity) < if(preg_match('/' . $profanity . '/i', $row['Name'])) < echo 'Bad word found!'; >>
Php — Check if all elements of one array exist in other, It returns all elements of the first array that do not exist in the second. If the result is empty, all items will exist in the other array. If the result is empty, all items will exist in the other array.
Check the element in the array and if it doesn’t exist out data into database
You are fetching it wrong way then assigning a whole array instead of the element you want to assign. It should be like this
while($login=mysql_fetch_assoc($logins)) < $logins_array[]=$login["login"]; //add only the relevant value, not the whole array. >
And in_array should look like
if(!(in_array($_POST['login'],$logins_array))) // without those extra quotes
Consider being more protective of your database though, this code is very vulnerable with that INSERT
Php: check if certain item in an array is empty, PHP check if array index in variable has a value | isset() always returning true . 2. How to insert multiple rows of student records scores in a while loop in a database table?-4. Empty Array won’t be «empty» Related. 4673. How do I check if an array includes a value in JavaScript? 2914. Deleting an element from …
Check if elements are in a array and increment
Loop through the records, and check for the names
foreach($records as $record)< if (in_array("Sally", $record)) < //increase weight >else < //push to array >>
Completeley untested and might not do exactly what you want but this will set you on the right path.
$contains = FALSE; $contains = findNames($array, $firstName, $lastName); if($contains === TRUE) < // Add your weight to the array here >else < // Do something else or nothing >function findNames($array, $firstName, $lastName) < foreach($array as $arrayValues=>$arrayValue) < if($arrayValue['n1'] == $firstName || $arrayValue['n1'] == $lastName || $arrayValue['n2'] == $firstName || $arrayValue['n2'] == $lastName) < return TRUE; >else < return FALSE; >>
function findNames($array, $firstName, $lastName) < if(in_array($firstName, $array) || in_array($lastName, $array)) < return TRUE; >else
How, Teams. Q&A for work. Connect and share knowledge within a single location that is structured and easy to search. Learn more
in_array
Searches for needle in haystack using loose comparison unless strict is set.
Parameters
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 in_array() function will also check the types of the needle in the haystack .
Note:
Prior to PHP 8.0.0, a string needle will match an array value of 0 in non-strict mode, and vice versa. That may lead to undesireable results. Similar edge cases exist for other types, as well. If not absolutely certain of the types of values involved, always use the strict flag to avoid unexpected behavior.
Return Values
Returns true if needle is found in the array, false otherwise.
Examples
Example #1 in_array() example
$os = array( «Mac» , «NT» , «Irix» , «Linux» );
if ( in_array ( «Irix» , $os )) echo «Got Irix» ;
>
if ( in_array ( «mac» , $os )) echo «Got mac» ;
>
?>?php
The second condition fails because in_array() is case-sensitive, so the program above will display:
Example #2 in_array() with strict example
if ( in_array ( ‘12.4’ , $a , true )) echo «‘12.4’ found with strict check\n» ;
>
if ( in_array ( 1.13 , $a , true )) echo «1.13 found with strict check\n» ;
>
?>
The above example will output:
1.13 found with strict check
Example #3 in_array() with an array as needle
if ( in_array (array( ‘p’ , ‘h’ ), $a )) echo «‘ph’ was found\n» ;
>
if ( in_array (array( ‘f’ , ‘i’ ), $a )) echo «‘fi’ was found\n» ;
>
if ( in_array ( ‘o’ , $a )) echo «‘o’ was found\n» ;
>
?>
The above example will output:
See Also
- array_search() — Searches the array for a given value and returns the first corresponding key if successful
- isset() — Determine if a variable is declared and is different than null
- array_key_exists() — Checks if the given key or index exists in the array
User Contributed Notes 8 notes
Loose checking returns some crazy, counter-intuitive results when used with certain arrays. It is completely correct behaviour, due to PHP’s leniency on variable types, but in «real-life» is almost useless.
The solution is to use the strict checking option.
$array = array(
‘egg’ => true ,
‘cheese’ => false ,
‘hair’ => 765 ,
‘goblins’ => null ,
‘ogres’ => ‘no ogres allowed in this array’
);
// Loose checking — return values are in comments
// First three make sense, last four do not
in_array ( null , $array ); // true
in_array ( false , $array ); // true
in_array ( 765 , $array ); // true
in_array ( 763 , $array ); // true
in_array ( ‘egg’ , $array ); // true
in_array ( ‘hhh’ , $array ); // true
in_array (array(), $array ); // true
in_array ( null , $array , true ); // true
in_array ( false , $array , true ); // true
in_array ( 765 , $array , true ); // true
in_array ( 763 , $array , true ); // false
in_array ( ‘egg’ , $array , true ); // false
in_array ( ‘hhh’ , $array , true ); // false
in_array (array(), $array , true ); // false
I got an unexpected behavior working with in_array. I’m using following code:
// .
$someId = getSomeId (); // it gets generated/fetched by another service, so I don’t know what value it will have. P.S.: it’s an integer
// The actual data in my edge-case scenario:
// $someId = 0;
// $anyArray = [‘dataOne’, ‘dataTwo’];
if ( in_array ( $someId , $anyArray )) // do some work
>
// .
?>
With PHP7.4, in_array returns boolean true.
With PHP8.1, in_array returns boolean false.
It took me quite some time to find out what’s going on.
I found out that in_array will *not* find an associative array within a haystack of associative arrays in strict mode if the keys were not generated in the *same order*:
$needle = array(
‘fruit’ => ‘banana’ , ‘vegetable’ => ‘carrot’
);
$haystack = array(
array( ‘vegetable’ => ‘carrot’ , ‘fruit’ => ‘banana’ ),
array( ‘fruit’ => ‘apple’ , ‘vegetable’ => ‘celery’ )
);
echo in_array ( $needle , $haystack , true ) ? ‘true’ : ‘false’ ;
// Output is ‘false’
echo in_array ( $needle , $haystack ) ? ‘true’ : ‘false’ ;
// Output is ‘true’
?>
I had wrongly assumed the order of the items in an associative array were irrelevant, regardless of whether ‘strict’ is TRUE or FALSE: The order is irrelevant *only* if not in strict mode.
I’d like to point out that, if you’re using Enum data structures and want to compare whether an array of strings has a certain string Enum in it, you need to cast it to a string.
From what I’ve tested, the function works correctly:
if the array is filled with strings and you’re searching for a string;
if the array is filled with Enums and you’re searching for an Enum.
Here is a recursive in_array function:
$myNumbers = [
[ 1 , 2 , 3 , 4 , 5 ],
[ 6 , 7 , 8 , 9 , 10 ],
];
$array = [
‘numbers’ => $myNumbers
];
// Let’s try to find number 7 within $array
$hasNumber = in_array ( 7 , $array , true ); // bool(false)
$hasNumber = in_array_recursive ( 7 , $array , true ); // bool(true)
function in_array_recursive ( mixed $needle , array $haystack , bool $strict ): bool
foreach ( $haystack as $element ) if ( $element === $needle ) return true ;
>
$isFound = false ;
if ( is_array ( $element )) $isFound = in_array_recursive ( $needle , $element , $strict );
>
if ( $isFound === true ) return true ;
>
>
If you’re creating an array yourself and then using in_array to search it, consider setting the keys of the array and using isset instead since it’s much faster.
$slow = array( ‘apple’ , ‘banana’ , ‘orange’ );
if ( in_array ( ‘banana’ , $slow ))
print( ‘Found it!’ );
$fast = array( ‘apple’ => ‘apple’ , ‘banana’ => ‘banana’ , ‘orange’ => ‘orange’ );
if (isset( $fast [ ‘banana’ ]))
print( ‘Found it!’ );
Check if an Array contains a value in PHP
This tutorial will discuss about unique ways to check if an array contains a value in php.
Table Of Contents
Method 1: Using in_array() function
The in_array() function in PHP, accepts a value and an array as arguments, and returns true , if the value exists in the array. So, we can use this to check if an array contains a value or not in PHP.
Let’s see the complete example,
Frequently Asked:
Yes, Value exists in the array
As the value exists in the array, therefore it returned the boolean value true.
Method 2: Using array_search() function
The array_search() function in PHP, accepts a value and an array as arguments, and returns the key/index of first occurrence of given value in array . If the value does not exists in the array, then it returns false . So, we can use this to check if an array contains a value or not in PHP.
Let’s see the complete example,
Yes, Value exists in the array
As the value exists in the array, therefore it didn’t returned the boolean value false.
Summary
We learned about two different ways to check if a value exists in an array in PHP.
Related posts:
Share your love
Leave a Comment Cancel Reply
This site uses Akismet to reduce spam. Learn how your comment data is processed.
Terms of Use
Disclaimer
Copyright © 2023 thisPointer
To provide the best experiences, we and our partners use technologies like cookies to store and/or access device information. Consenting to these technologies will allow us and our partners to process personal data such as browsing behavior or unique IDs on this site and show (non-) personalized ads. Not consenting or withdrawing consent, may adversely affect certain features and functions.
Click below to consent to the above or make granular choices. Your choices will be applied to this site only. You can change your settings at any time, including withdrawing your consent, by using the toggles on the Cookie Policy, or by clicking on the manage consent button at the bottom of the screen.
The technical storage or access is strictly necessary for the legitimate purpose of enabling the use of a specific service explicitly requested by the subscriber or user, or for the sole purpose of carrying out the transmission of a communication over an electronic communications network.
The technical storage or access is necessary for the legitimate purpose of storing preferences that are not requested by the subscriber or user.
The technical storage or access that is used exclusively for statistical purposes. The technical storage or access that is used exclusively for anonymous statistical purposes. Without a subpoena, voluntary compliance on the part of your Internet Service Provider, or additional records from a third party, information stored or retrieved for this purpose alone cannot usually be used to identify you.
The technical storage or access is required to create user profiles to send advertising, or to track the user on a website or across several websites for similar marketing purposes.