Check if string is equal to one of many given strings - php

I want to check whether string is one of the given strings. It would look something like this.
$string 'test';
// if given string is 'test' function will return false.
function checkIfIsSubstring($string)
{
if (strcmp($string, 'test2') )
return true;
if (strcmp($string, 'test3') )
return true;
if (strcmp($string, 'test4') )
return true;
return false;
}
is there php function what would do same thing, without me creating a new function?

You can put the values into an array and then use in_array():
$array = array('test1', 'test2', 'test3');
$string = 'test1';
if(in_array($string, $array)) {
// do something
}

Related

How to check multiple values in an array with AND , OR operators

I'm looking to see if an array has one or more values inside it and I want to pass check my values are in that array. I'm going to use it to check role permissions in a system.
example input-output:
[1,2,3,4,5,6].include?([4,1]) => true
[4,1,6,2].include?([4,1]) => true
[3,4,7].include?([4,1]) => false
I tried to solve it using in_array():
if(!$auth->checkPermissions([1,3])) {
echo json_encode(['Result'=>false,'Type'=>'ERROR','Message'=>UNAUTHORIZED_ACCESS]);
exit;
}
public static function checkPermissions($permissionLevels = []){
$userPermission =[1,4,5,6];
foreach($permissionLevels as $permission){
if (in_array($permission,$userPermission)) {
return true;
} else {
return false;
}
}
return false;
}
Your problem is happening because you only checking 1 permission as you use return in the foreach.
You should do it like this:
public static function checkPermissions($permissionLevels = []){
$userPermission =[1,4,5,6];
foreach($permissionLevels as $permission){
if (!in_array($permission,$userPermission))
return false; // if one is missing decline
}
return true; // if got here mean all found
}
You can also use array-intersect as:
function checkPermissions($permissionLevels = []){
$userPermission =[1,4,5,6];
$permissionLevels = array_unique($permissionLevels);
return count(array_intersect($permissionLevels, $userPermission)) == count($permissionLevels));
}
Do notice to use array_unique if using the array_intersect as you can have duplicate - consider case where checkPermissions([4,4]);
Just compare the intersection of the two with the permissions to be checked:
return array_intersect($permissionLevels, $userPermission) == $permissionLevels;
See the Demo.

Maintain Element in PHP Array And Update in PHP Class

I have one PHP class as below (part of the code):
class myclass{
private static $arrX = array();
private function is_val_exists($needle, $haystack) {
if(in_array($needle, $haystack)) {
return true;
}
foreach($haystack as $element) {
if(is_array($element) && $this->is_val_exists($needle, $element))
return true;
}
return false;
}
//the $anInput is a string e.g. Michael,18
public function doProcess($anInput){
$det = explode(",", $anInput);
if( $this->is_val_exists( $det[0], $this->returnProcess() ) ){
//update age of Michael
}
else{
array_push(self::$arrX, array(
'name' => $det[0],
'age' => $det[1]
));
}
}
public function returnProcess(){
return self::$arrX;
}
}
The calling code in index.php
$msg = 'Michael,18';
myclass::getHandle()->doProcess($msg);
In my webpage says index.php, it calls function doProcess() over and over again. When the function is called, string is passed and stored in an array. In the next call, if let's say same name is passed again, I want to update his age. My problem is I don't know how to check if the array $arrX contains the name. From my own finding, the array seems to be re-initiated (back to zero element) when the code is called. My code never does the update and always go to the array_push part. Hope somebody can give some thoughts on this. Thank you.
There is a ) missing in your else condition of your doProcess() function, it should read:
else{
array_push(self::$arrX, array(
'name' => $det[0],
'age' => $det[1]
)); // <-- there was the missing )
}
Here is a complete running solution based on your code:
<?php
class myclass{
private static $arrX = array();
private function is_val_exists($needle, $haystack) {
if(in_array($needle, $haystack)) {
return true;
}
foreach($haystack as $element) {
if(is_array($element) && $this->is_val_exists($needle, $element))
return true;
}
return false;
}
//the $anInput is a string e.g. Michael,18
public function doProcess($anInput){
$det = explode(",", $anInput);
if( $this->is_val_exists( $det[0], $this->returnProcess() ) ){
//update age of Michael
for ($i=0; $i<count(self::$arrX); $i++) {
if (is_array(self::$arrX[$i]) && self::$arrX[$i]['name'] == $det[0]) {
self::$arrX[$i]['age'] = $det[1];
break;
}
}
} else{
array_push(self::$arrX, array(
'name' => $det[0],
'age' => $det[1]
));
}
}
public function returnProcess(){
return self::$arrX;
}
}
$mc = new myclass();
$mc->doProcess('Michael,18');
$mc->doProcess('John,23');
$mc->doProcess('Michael,19');
$mc->doProcess('John,25');
print_r($mc->returnProcess());
?>
You can test it here: PHP Runnable
As I said in comments, it looks like you want to maintain state between requests. You can't use pure PHP to do that, you should use an external storage solution instead. If it's available, try Redis, it has what you need and is quite simple to use. Or, if you're familiar with SQL, you could go with MySQL for example.
On a side note, you should read more about how PHP arrays work.
Instead of array_push, you could have just used self::$arrX[] = ...
Instead of that, you could have used an associative array, e.g. self::$arrX[$det[0]] = $det[1];, that would make lookup much easier (array_key_exists etc.)
Can you try updating the is_val_exists as follows:
private function is_val_exists($needle, $haystack) {
foreach($haystack as $element) {
if ($element['name'] == $needle) {
return true;
}
return false;
}

PHP - Find array by name given as string

I've got some arrays like this
$something = array('foo' => 'bar');
Now how can I get the content of $something? I want to use this method to retrieve values from arrays but can't work out how to find an array with only it's name given as a string.
getArrayData($array,$key){
// $array == 'something';
// $key == 'foo';
// this should return 'bar'
}
EDIT:
I abstracted this too much maybe, so here is the full code:
class Config {
public static $site = array(
'ssl' => 'true',
'charset' => 'utf-8',
// ...
);
public static $menu = array(
'home' => '/home',
'/hub' => '/hub',
// ...
);
public static function get($from, $key){
return self::$from[$key];
}
public static function __callStatic($method, $key){
return self::get($method,$key);
}
}
In the end the configuration should be accessible from within the whole app by using Config::site('charset') to return 'utf-8'
You can use Variable-Variables
<?php
$something = array('foo' => 'bar');
$key="foo";
$arrayName="something";
echo getArrayData($$arrayName,$key); // Notice the use of $$
function getArrayData($array,$key){
return isset($array[$key])? $array[$key] : NULL ;
}
Fiddle
$array == 'something' doesn't mean much, you can easily check the array keys and return the value if the key exists:
function getArrayData($array,$key){
if(isset($array[$key])) return $array[$key];
else return "";
}
You should pass the array itself as parameter instead of the name. Then you can just return the value by the given key:
function getArrayData($array,$key){
return $array[$key];
}

filter array values from a dictionary

I have an $array on php, and I'd like to know if the values are from a specific dictionary.
For example, if my dictionary is an array of values ['cat', 'dog', 'car', 'man'] I'd like to filter my $array and return false if a word into this one is not on the dictionary.
So, if $array is :
['men', 'cat'] // return false;
['man', 'cat'] // return true;
['cat', 'dogs'] // return false;
[''] // return false;
and so on...
How can I filter an array in this manner?
function checkDictionary($array,$dictionary){
foreach($array as $array_item){
if(!in_array($array_item,$dictionary)){
return false;
}
}
return true;
}
you can also do something like:
function checkDictionary($array,$dictionary){
$result = (empty(array_diff($array,$dictionary))) ? true : false;
return $result;
}
To increase performance, you should convert you "dictionary" to an associative array, where the keys are the words in the dictionary:
$dict = array_flip($dict);
Then all you have to do is to loop over the values you search for, which is O(n):
function contains($search, $dict) {
foreach($search as $word) {
if(!array_key_exists($word, $dict)) {
return false;
}
return true;
}
Reference: array_flip, array_key_exists
function doValuesExist($dictionary, $array) {
return (count(array_intersect($dictionary,$array)) == count($array));
}

More concise way to check to see if an array contains only numbers (integers)

How do you verify an array contains only values that are integers?
I'd like to be able to check an array and end up with a boolean value of true if the array contains only integers and false if there are any other characters in the array. I know I can loop through the array and check each element individually and return true or false depending on the presence of non-numeric data:
For example:
$only_integers = array(1,2,3,4,5,6,7,8,9,10);
$letters_and_numbers = array('a',1,'b',2,'c',3);
function arrayHasOnlyInts($array)
{
foreach ($array as $value)
{
if (!is_int($value)) // there are several ways to do this
{
return false;
}
}
return true;
}
$has_only_ints = arrayHasOnlyInts($only_integers ); // true
$has_only_ints = arrayHasOnlyInts($letters_and_numbers ); // false
But is there a more concise way to do this using native PHP functionality that I haven't thought of?
Note: For my current task I will only need to verify one dimensional arrays. But if there is a solution that works recursively I'd be appreciative to see that to.
$only_integers === array_filter($only_integers, 'is_int'); // true
$letters_and_numbers === array_filter($letters_and_numbers, 'is_int'); // false
It helps to define two helper, higher-order functions:
/**
* Tell whether all members of $elems validate the $predicate.
*
* all(array(), 'is_int') -> true
* all(array(1, 2, 3), 'is_int'); -> true
* all(array(1, 2, 'a'), 'is_int'); -> false
*/
function all($elems, $predicate) {
foreach ($elems as $elem) {
if (!call_user_func($predicate, $elem)) {
return false;
}
}
return true;
}
/**
* Tell whether any member of $elems validates the $predicate.
*
* any(array(), 'is_int') -> false
* any(array('a', 'b', 'c'), 'is_int'); -> false
* any(array(1, 'a', 'b'), 'is_int'); -> true
*/
function any($elems, $predicate) {
foreach ($elems as $elem) {
if (call_user_func($predicate, $elem)) {
return true;
}
}
return false;
}
<?php
$only_integers = array(1,2,3,4,5,6,7,8,9,10);
$letters_and_numbers = array('a',1,'b',2,'c',3);
function arrayHasOnlyInts($array){
$test = implode('',$array);
return is_numeric($test);
}
echo "numbers:". $has_only_ints = arrayHasOnlyInts($only_integers )."<br />"; // true
echo "letters:". $has_only_ints = arrayHasOnlyInts($letters_and_numbers )."<br />"; // false
echo 'goodbye';
?>
Another alternative, though probably slower than other solutions posted here:
function arrayHasOnlyInts($arr) {
$nonints = preg_grep('/\D/', $arr); // returns array of elements with non-ints
return(count($nonints) == 0); // if array has 0 elements, there's no non-ints
}
There's always array_reduce():
array_reduce($array, function($a, $b) { return $a && is_int($b); }, true);
But I would favor the fastest solution (which is what you supplied) over the most concise.
function arrayHasOnlyInts($array) {
return array_reduce(
$array,
function($result,$element) {
return is_null($result) || $result && is_int($element);
}
);
}
returns true if array has only integers, false if at least one element is not an integer, and null if array is empty.
Why don't we give a go to Exceptions?
Take any built in array function that accepts a user callback (array_filter(), array_walk(), even sorting functions like usort() etc.) and throw an Exception in the callback. E.g. for multidimensional arrays:
function arrayHasOnlyInts($array)
{
if ( ! count($array)) {
return false;
}
try {
array_walk_recursive($array, function ($value) {
if ( ! is_int($value)) {
throw new InvalidArgumentException('Not int');
}
return true;
});
} catch (InvalidArgumentException $e) {
return false;
}
return true;
}
It's certainly not the most concise, but a versatile way.

Categories