I have a simple function that should just give me TRUE or FALSE if a value is find in an array.
function bypass($user, $bypassUsers){
$users = explode(",", $bypassUsers);
// trim($users);
if(in_array($user,$users)){
return true;
} else {
return false;
}
}
While to me everything looks of when I have more than 2 values in the array, the function returns FALSE as if in_array() does not see from key [2].
Any idea?
If you want to apply trim to all elements, instead of:
$users = explode(",", $bypassUsers);
trim($users);
You should do this instead:
$users = array_map('trim', explode(',', $bypassUsers));
It applies trim() to the result of explode(). Afterwards, you can return the result in one statement:
return in_array($user, $users, true);
// third argument determines whether to use == or === for comparison
function bypass($user, $bypassUsers){
$users = explode(",", $bypassUsers);
foreach($users as $key=>$usr){
$users[$key] = trim($usr);
}
if(in_array(trim($user),$users)){
return true;
} else {
return false;
}
}
Trim is the problem because it works with string not with an array
Related
i am trying to create function to check if array element is the last array element in one array. Original array looks like:
array(1001,
1002,
array('exam'=>true, 'index'=>10),
1003,
1004,
1005,
array('exam'=>true, 'index'=>20),
1006,
1007,
array('exam'=>true, 'index'=>30),
1008,
1009
)
I this case to prove if "array('exam'=>true, 'index'=>30)" is the last.
I have index position of that element, but I do not know how to check if that is the last array element.
function is_last_exam_in_survey($array, $exam_position) {
foreach($array as $element) {
if(!is_numeric($element) {
// check if that is the last array element in array
//return true;
} else {
// return false;
}
}
}
I would be grateful for any advice:)
function get_last_exam_in_survey($array) {
$last = null;
foreach($array as $element) {
if(is_array($element) && !empty($element['exam'])) {
$last = $element;
}
}
return $last;
}
function is_last_exam_in_survey($array, $exam_position) {
$last_exam = get_last_exam_in_survey($array);
return !empty($last_exam) && ($last_exam['index']==$exam_position);
}
I think this would be the quickest solution:
function is_last_exam_in_survey($array, $exam_position) {
$last_index = array_key_last( $array );
if( $exam_position == $last_index ){
return true;
}else{
return false;
}
}
You can still change the conditional statement if you are trying to compare values from the last element, for example:
if( isset($last_index['index']) && $exam_position == $last_index['index'] ){
Also, if you want to get the latest array value instead of key, you could use this:
$last_index = end( $array );
I would reverse the array, and look for the first element. Something like:
function is_last_exam_in_survey($array, $exam_position) {
foreach(array_reverse($array) as $element) {
if(!is_numeric($element) {
return $element['index'] === $exam_position;
}
}
return false;
}
Seems like the most efficient and simplest solution to me.
this solution avoid loop. at first we find out the last index of array.Then we use is_array() function for check the last element is array or not.
function get_last_exam_in_survey(array $arr)
{
$lastOfset = count($arr) - 1;
if(is_array($arr[$lastOfset])){
return true;
}else{
return false;
}
}
I think you can use array_column function to do that
function is_last_exam_in_survey($array,$exam_position){
$ac = array_column($array, 'index'); // return array(10,20,30)
$la = $ac[count($ac) - 1]; // 30
foreach ($array as $element) {
if (!is_numeric($element)) {
// check if $element['index'] === 30
if($element['index'] === $la){
return true;
}
}
}
}
How about using array_slice to extract the values in the array that are after the position you are looking at, then array_filter to remove any values that are not arrays. If there are any values left, then the entry you are looking at is not the last array entry in the array.
This may not be very efficient if you are calling it a lot of times with a large array. It may be better to rethink the way the data is stored or loaded into the array.
function is_last_exam_in_survey($array, $exam_position)
{
return isset($array[$exam_position])
&& is_array($array[$exam_position])
&& !array_filter(array_slice($array, $exam_position + 1), 'is_array');
}
I have this function to check for word sequences:
function sequence($arr_scheme = [], $arr_input = [])
{
$sequence_need = array_values(array_intersect($arr_scheme, $arr_input));
if(!empty($arr_input) && ($sequence_need == $arr_input)):
return true;
else:
return false;
endif;
}
There were my sample and scheme variables:
$sample = "branch of science";
$scheme = "The branch of science concerned of nature and property of matter and energy";
I have converted to array:
$arr_sample = explode(" ",trim(rtrim(rtrim($sample,".")," ")));
echo 'Sample:';
var_dump($arr_sample);
$arr_scheme = explode(" ",trim(rtrim(rtrim($scheme,".")," ")));
echo '<br/>Scheme:';
var_dump($arr_scheme);
Now, I check the sequences:
$result = sequence($arr_scheme, $arr_sample);
The result:
echo '<br/>Result:';
var_dump($result);
When I set the variable $sample to
"branch science" the result will return true. This was fine.
However when I set the variable sample to
"branch of science" the result will return false .
Reason - the word of was more than 1, how I can solve this problem?
Find first input word in the scheme (can be multiple).
Then run recursive for rests of arrays.
function sequence($arr_scheme = [], $arr_input = [])
{
if (!$arr_input) return true;
$first = array_shift($arr_input);
$occurences = array_keys($arr_scheme, $first);
if (!$occurences) return false;
foreach ($occurences as $o) { // loop first word occurences
$found = sequence(array_slice($arr_scheme, $o), $arr_input);
if ($found) return true;
}
return false;
}
First word later occurences should not matter anything for match.
So, this tail-recursion function will work even better:
function sequence($arr_scheme = [], $arr_input = [])
{
if (!$arr_input) return true;
$first = array_shift($arr_input);
$index = array_search($arr_scheme, $first);
if ($index === false) return false; // not found
return sequence(array_slice($arr_scheme, $index), $arr_input);
}
You can research more at here. Note: "Returns an array containing all of the values in array1 whose values exist in all of the parameters.". Then, look at in your result, when you call var_dump($arr_scheme);, you see "of" appears 3 times. and size of array result after compare is 5. however, size of array $sample is 3. So, you can understand why it returns false.
Solution for this case. why dont you try to use regular expression? or strpos function?
$sequence_need = array_unique($sequence_need);
array_unique removes any duplicate values in your array.. the duplicate 'of' will be removes.. Hope it helps..
I think you should go with array_diff(). It computes the difference of arrays and returns the values in $arr_sample that are not present in $arr_scheme.
So,
array_diff($arr_sample, $arr_scheme)
will return an empty array if all the values in $arr_sample are present in $arr_scheme
The next step would be to count the length of the array returned by array_diff(). If it equals 0, then we should return true
return count(array_diff($arr_sample, $arr_scheme)) === 0;
The above return statement could be presented as:
$diff = array_diff($arr_sample, $arr_scheme);
if (count($diff) === 0) {
return true;
} else {
return false;
}
From your comments it became clear that your function should return true
if all the elements of $arr_input are present in $arr_scheme in the same order
that they appear in $arr_scheme. Othewise it should return false
So,
sequence(['branch', 'of', 'science', 'and', 'energy'], ['branch', 'of', 'energy'])
should return true
and
sequence(['branch', 'of', 'science', 'and', 'energy'], ['science', 'of', 'branch'])
should return false
In this case the function sequence() could be defined as follows:
function sequence($arr_scheme = [], $arr_input = [])
{
//test if all elements of $arr_input are present in $arr_scheme
$diff = array_diff($arr_input, $arr_scheme);
if ($diff) {
return false;
}
foreach ($arr_input as $value) {
$pos = array_search($value, $arr_scheme);
if (false !== $pos ) {
$arr_scheme = array_slice($arr_scheme, $pos + 1);
continue;
}
return false;
}
return true;
}
I have an array
$data = array( 'a'=>'0', 'b'=>'0', 'c'=>'0', 'd'=>'0' );
I want to check if all array values are zero.
if( all array values are '0' ) {
echo "Got it";
} else {
echo "No";
}
Thanks
I suppose you could use array_filter() to get an array of all items that are non-zero ; and use empty() on that resulting array, to determine if it's empty or not.
For example, with your example array :
$data = array(
'a'=>'0',
'b'=>'0',
'c'=>'0',
'd'=>'0' );
Using the following portion of code :
$tmp = array_filter($data);
var_dump($tmp);
Would show you an empty array, containing no non-zero element :
array(0) {
}
And using something like this :
if (empty($tmp)) {
echo "All zeros!";
}
Would get you the following output :
All zeros!
On the other hand, with the following array :
$data = array(
'a'=>'0',
'b'=>'1',
'c'=>'0',
'd'=>'0' );
The $tmp array would contain :
array(1) {
["b"]=>
string(1) "1"
}
And, as such, would not be empty.
Note that not passing a callback as second parameter to array_filter() will work because (quoting) :
If no callback is supplied, all entries of input equal to FALSE (see
converting to boolean) will be removed.
How about:
// ditch the last argument to array_keys if you don't need strict equality
$allZeroes = count( $data ) == count( array_keys( $data, '0', true ) );
Use this:
$all_zero = true;
foreach($data as $value)
if($value != '0')
{
$all_zero = false;
break;
}
if($all_zero)
echo "Got it";
else
echo "No";
This is much faster (run time) than using array_filter as suggested in other answer.
you can loop the array and exit on the first non-zero value (loops until non-zero, so pretty fast, when a non-zero value is at the beginning of the array):
function allZeroes($arr) {
foreach($arr as $v) { if($v != 0) return false; }
return true;
}
or, use array_sum (loops complete array once):
function allZeroes($arr) {
return array_sum($arr) == 0;
}
#fireeyedboy had a very good point about summing: if negative values are involved, the result may very well be zero, even though the array consists of non-zero values
Another way:
if(array_fill(0,count($data),'0') === array_values($data)){
echo "All zeros";
}
Another quick solution might be:
if (intval(emplode('',$array))) {
// at least one non zero array item found
} else {
// all zeros
}
if (!array_filter($data)) {
// empty (all values are 0, NULL or FALSE)
}
else {
// not empty
}
I'm a bit late to the party, but how about this:
$testdata = array_flip($data);
if(count($testdata) == 1 and !empty($testdata[0])){
// must be all zeros
}
A similar trick uses array_unique().
You can use this function
function all_zeros($array){//true if all elements are zeros
$flag = true;
foreach($array as $a){
if($a != 0)
$flag = false;
}
return $flag;
}
You can use this one-liner: (Demo)
var_export(!(int)implode($array));
$array = [0, 0, 0, 0]; returns true
$array = [0, 0, 1, 0]; returns false
This is likely to perform very well because there is only one function call.
My solution uses no glue when imploding, then explicitly casts the generated string as an integer, then uses negation to evaluate 0 as true and non-zero as false. (Ordinarily, 0 evaluates as false and all other values evaluate to true.)
...but if I was doing this for work, I'd probably just use !array_filter($array)
This is killing me. It seems so simple, but for some reason I cannot get it to work.
Basically what I have is a function that accepts a single string $name as a variable, then it goes through and checks that variable against values in an array. If the variable is found in the array is returns TRUE. This function is called from within a foreach loop in another function (which submits a new $name variable each time.)
I have tried 3 different ways to check the variable against the array but it never works properly.
1.) using another foreach() loop
function check($name) {
$commaSeparatedString = 'First Name, Second Name, Third Name';
$array = explode(",", $commaSeparatedString);
foreach($array as $arrayValue) {
if($arrayValue == $name) {
return TRUE;
}
else {
return FALSE;
}
}
}
2.) using in_array()
function check($name) {
$commaSeparatedString = 'First Name, Second Name, Third Name';
$array = explode(",", $commaSeparatedString);
if(in_array($name, $array, TRUE)) {
return TRUE;
}
else {
return FALSE;
}
}
3.) looping through each value in the array manually and checking for a match
function check($name) {
$commaSeparatedString = 'First Name, Second Name, Third Name';
$array = explode(",", $commaSeparatedString);
$count = count($array);
$i = 0;
while($i<=$count) {
if(isset($array[$i]) && $array[$i] == $name) {
$i++;
echo $i;
return TRUE;
break;
}
else {
$i++;
echo $i;
return FALSE; }
}
}
Here a simplified part of the function where check() is run:
function loopCheck() {
$group = array($obj1, $obj2, $obj3, $obj4, $obj5);
foreach($group as $groupValue) {
$name = $groupValue->name;
$ignore = $this->check($name);
if($ignore == TRUE) { }
else { echo $name; }
}
}
The result for all three variations of check() is the same. It returns TRUE for every $groupValue except the first value of $array. So if the $name of $obj2 was 'First Name' it would return TRUE, but if the $name of $obj3 was 'Second Name' is still returns FALSE. I echoed $i for the third variation at one point and the value consistently stayed at 1, so I know there is some error with that method, but I don't know why the result would be the same using the other 2 methods.
There are several issues with your code. The one that causes the failure of all code, is that you explode by ',', thus leaving a whitespace in your strings. You should explode on ', '.
But the first code is erroneous still: The foreach will return on the first iteration, always, thus checking only the first element. The loop should be:
foreach ($array as $arrayValue) {
if ($arrayValue == $name) {
return true;
}
}
return false;
Same applies to your last code.
The best variant is probably the second, here is a slightly shorter, adjusted variant:
function check($name) {
$commaSeparatedString = 'First Name, Second Name, Third Name';
return in_array($name, explode(', ', $commaSeparatedString), true));
}
You should not put
Return false;
On your else, you should put it after the whole loop.
Also keep in mind that if you wanna explode a, b, c to be [a,b,c] you have to use
explode(", ",$str); //note the space
The problem is that when you make the explode in the check function, some pieces have spaces because there is a space after the comma.
Did you trim() your strings?
It would work on the first string as it starts with "First String" but the second explode()ed string would be "spaceSecond String".
I think any of those techniques will work, but you just have small errors.
I've fixed the first one below. You don't want to return false in an else clause. you want it AFTER the foreach loop, only if it fails to match EVERY time.
function check($name) {
$commaSeparatedString = 'First Name, Second Name, Third Name';
$array = explode(",", $commaSeparatedString);
foreach($array as $arrayValue) {
if($arrayValue == $name) {
return TRUE;
}
}
return false;
}
The in_array version is potentially simpler. Notice that there is no reason for if ($val) {return true;} else {return false;}, just do return $val
function check($name)
{
$csvs = 'First Name, Second Name, Third Name';
return in_array($name, explode(', ', $csv));
//return in_array(trim(strtoupper($name)), array_map('trim', explode(', ', strtoupper($csv))));
//try this second way is kind of over-kill thorough, but try it if you still get false where true is expected
}
You also have to either trim the strings of the array you make or explode(', ' $csv) with a space. Otherwise the elements of array will have a leading space.
I have an issue here with filter_array.
below is my code:
$array = array("0","0","1");
function returnzero($d){
if($d=='0'){
return $d;
}
}
$all_zeros = array_filter($array, "returnzero");
echo count($all_zeros);
I would like to filter out all values that none other than zero.
Above is my code. However, the count result returned is always 0.
may I know what is my mistake?
Thanks.
See the documentation on array_filter
You need to be returning true or false, not the number... So your function becomes:
function returnzero($d) { return $d == 0; }
You need to check $d != 0 and it will return all the non-zero values. Trying to return 0 is the same as returning false, so it fails.
Function must returns TRUE.
$array = array(0, 0, 1);
function returnzero($d){
if($d=='0'){
return true;
}
}
$all_zeros = array_filter($array, "returnzero");
echo count ($all_zeros);
Modify the return value to reflect the purpose:
function iszero($d) { return $d == '0'; }
$all_zeros = array_filter($array, 'iszero');
Regards
rbo
The function you pass into array_filter() must return TRUE or FALSE to tell PHP whether the current value being checked matches what you're filtering for. You're returning the number that was passed in. Since you're checking for zeroes, you're returning zero, which PHP interprets as FALSE. You could rewrite the function as follows:
if ($d == 0) {
return TRUE;
} else {
return FALSE;
}
or more concisely
return ($d == 0);