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
}
Related
I am trying to compare a values in array and select the next value in the array based on a selected value.
For example
array(05:11,05:21,05:24,05:31,05:34,05:41,05:44,05:50,05:54);
and if the the search value is for example 05:34, the one that is returned to be 05:41. If the value is 05:50, 05:54 is returned
I did find something that might help me on this post, but because of the : in my values it will not work.
Any ideas how can I get this to work?
function getClosest($search, $arr) {
$closest = null;
foreach ($arr as $item) {
if ($closest === null || abs($search - $closest) > abs($item - $search)) {
$closest = $item;
}
}
return $closest;
}
UPDATE
Maybe I should somehow convert the values in the array in something more convenient to search within - Just a thinking.
Using the internal pointer array iterator -which should be better from the performance point of view than array_search- you can get the next value like this:
$arr = array('05:11','05:21','05:24','05:31','05:34','05:41','05:44','05:50','05:54');
function getClosest($search, $arr) {
$item = null;
while ($key = key($arr) !== null) {
$current = current($arr);
$item = next($arr);
if (
strtotime($current) < strtotime($search) &&
strtotime($item) >= strtotime($search)
) {
break;
} else if (
strtotime($current) > strtotime($search)
) {
$item = $current;
break;
}
}
return $item;
}
print_r([
getClosest('05:50', $arr),
getClosest('05:34', $arr),
getClosest('05:52', $arr),
getClosest('05:15', $arr),
getClosest('05:10', $arr),
]);
This will output :-
Array (
[0] => 05:50
[1] => 05:34
[2] => 05:54
[3] => 05:21
[4] => 05:11
)
Live example https://3v4l.org/tqHOC
Using array_search() you can find index of array item based of it value. So use it to getting index of searched item.
function getClosest($search, $arr) {
return $arr[array_search($search, $arr)+1];
}
Update:
If search value not exist in array or search value is last item of array function return empty.
function getClosest($search, $arr) {
$result = array_search($search, $arr);
return $result && $result<sizeof($arr)-1 ? $arr[$result+1] : "";
}
Check result in demo
First convert your array value in string because of you use the ':' in the value like
array('05:11','05:21','05:24','05:31','05:34','05:41','05:44','05:50','05:54');
Then use below code to find the next value from the array
function getClosest($search, $arr) {
return $arr[array_search($search,$arr) + 1];
}
i have a problem with a php if condition
i have follow variables and arrays:
<?php
$appartamenti = array("97", "98", "99", "100");
$appartamentinoloft = array("97", "98", "99");
$case = array("103", "104", "107", "108");
$casevacanze = array("109", "110", "111", "112");
$stanze = array("115", "116");
$uffici = array("113", "114");
$locali = array("117", "118");
$garage = array("119", "120");
$terreni = array("121", "122");
$cantine = array("123", "124");
$tuttenoterreni = array($appartamenti, $case, $casevacanze, $uffici, $garage, $cantine);
?>
and i have this if condition:
<?php if ( osc_item_category_id() == $terreni) { ?>
<?php echo $custom_field_value['dimensioni-terreni'] ;?> mq
<?php } else if ( osc_item_category_id() == $tuttenoterreni) { ?>
<?php echo $custom_field_value['dimensioni'] ;?> mq
<?php } else { ?>
<?php } ?>
osc_item_category_id() is a number value
but not work.
i don't understand where is problem...
$terreni is single dimensional array and $tuttenoterreni is multi dimensional array.
For a single dimensional array, use in_array() function and for multi dimesnional array, create a custom function to find values in this multi dimensional array.
I've provided you the following code, which will help you to find values in multi dimensional array. Follow in_array() and multidimensional array
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;
}
Code:
<?php
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;
}
if (in_array(osc_item_category_id(),$terreni)) {
echo $custom_field_value['dimensioni-terreni'] ;
} elseif(in_array_r(osc_item_category_id(), $tuttenoterreni)) {
echo $custom_field_value['dimensioni'] ;
} else {
echo "Oops.!! No results found.";
}?>
Useful Links:
in_array() - PHP Manual
in_array() and multidimensional array
You can't check "directly" this. You are trying to compare two type of variables.
An PHP array is a pointer to "multiple variables".
If I read your code correctly, probably your function osc_item_category_id returns an integer. In that case, the first if will change to:
<?php if (in_array(osc_item_category_id(), $terreni)) { ?>
You can check documentation about in_array function here: http://be2.php.net/manual/en/function.in-array.php.
The elseif, have a similar problem. You've created a multidimensional array (an array of arrays). You need to use on this place the array_merge function (check documentation here: http://be2.php.net/manual/en/function.array-merge.php), to create a unique array with all values of the another ones. Then, you can check as on the first example:
$tuttenoterreni = array_merge($appartamenti, $case, $casevacanze, $uffici, $garage, $cantine);
<?php } else if (in_array(osc_item_category_id(), $tuttenoterreni)) { ?>
if osc_item_category_id() function return no. 121,122 user this function to compare.
<?php
$in_id = osc_item_category_id();
if(in_array($in_id,$terreni)){
echo $custom_field_value['dimensioni-terreni'];
}
?>
The in_array() function searches an array for a specific value.
Note: If the search parameter is a string and the type parameter is set to TRUE, the search is case-sensitive.
Syntax:
in_array(search,array,type)
Example :
$people = array("Peter", "Joe", "Glenn", "Cleveland");
if (in_array("Glenn", $people)){
echo "Match found";
}
Use the function
bool in_array ( value , array )
this function returns true is the value is present in the array
So modify the content of if and else if condition in your code, e.g:
if(in_array(osc_item_category_id() , $terreni ))
Also what I notice in your code is that in the elseif part you are trying to compare a numerical value returned by osc_item_category_id() with the value in the 'array of array', whereas in 'if' condition you are comparing the value returned by osc_item_category_id() with value in 'array'.
If it is the fact then in elseif part you need to run a foreach loop, comparing the value returned by 'osc_item_category_id()' with each array using the above 'in_array()' method.
Hope this help out!!!
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
I am trying to write a piece of code that searches one column of 2-D array values and returns the key when it finds it. Right now I have two functions, one to find a value and return a boolean true or false and another (not working) to return the key. I would like to merge the two in the sense of preserving the recursive nature of the finding function but returning a key. I cannot think how to do both in one function, but working key finder would be much appreciated.
Thanks
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;
}
function loopAndFind($array, $index, $search){
$returnArray = array();
foreach($array as $k=>$v){
if($v[$index] == $search){
$returnArray[] = $k;
}
}
return $returnArray;
}`
Sorry, I meant to add an example. For instance:
Array [0]{
[0]=hello
[1]=6
}
[1]
{
[0]=world
[1]=4
}
and I want to search the array by the [x][0] index to check each string of words for the search term. If found, it should give back the index/key in the main array like "world" returns 1
This works:
$array = array(array('hello', 6), array('world', 4));
$searchTerm = 'world';
foreach ($array as $childKey => $childArray) {
if ($childArray['0'] == $searchTerm) {
echo $childKey; //Your Result
}
}
You already have all you need in your first function. PHP does the rest:
$findings = array_map('in_array_r', $haystack);
$findings = array_filter($findings); # remove all not found
var_dump(array_keys($findings)); # the keys you look for
Is it possible to use array_map() to test values of an array? I want to make sure that all elements of an array are numeric.
I've tried both
$arrays = array(
array(0,1,2,3 )
, array ( 0,1, "a", 5 )
);
foreach ( $arrays as $arr ) {
if ( array_map("is_numeric", $arr) === FALSE ) {
echo "FALSE\n";
} else {
echo "TRUE\n";
}
}
and
$arrays = array(
array(0,1,2,3 )
, array ( 0,1, "a", 5 )
);
foreach ( $arrays as $arr ) {
if ( ( array_map("is_numeric", $arr) ) === FALSE ) {
echo "FALSE\n";
} else {
echo "TRUE\n";
}
}
And for both I get
TRUE
TRUE
Can this be done? If so, what am I doing wrong?
Note: I am aware that I can get my desired functionality from a foreach loop.
array_map returns an array. So it will always be considered 'true'. Now, if you array_search for FALSE, you might be able to get the desire effects.
From the PHP.net Page
array_map() returns an array containing all the elements of
arr1 after applying the callback function to each one.
This means that currently you have an array that contains true or false for each element. You would need to use array_search(false,$array) to find out if there are any false values.
I'm usually a big advocate of array_map(), array_filter(), etc., but in this case foreach() is going to be the best choice. The reason is that with array_map() and others it will go through the entire array no matter what. But for your purposes you only need to go through the array until you run into a value for which is_numeric() returns false, and as far as I know there's no way in PHP to break out of those methods.
In other words, if you have 1,000 items in your array and the 5th one isn't numeric, using array_map() will still check the remaining 995 values even though you already know the array doesn't pass your test. But if you use a foreach() instead and have it break on is_numeric() == false, then you'll only need to check those first five elements.
You could use filter, but it ends up with a horrible bit of code
$isAllNumeric = count(array_filter($arr, "is_numeric")) === count($arr)
Using a custom function makes it a bit better, but still not perfect
$isAllNumeric = count(array_filter($arr, function($x){return !is_numeric($x);})) === 0
But if you were using custom functions array_reduce would work, but it still has some failings.
$isAllNumeric = array_reduce($arr,
function($x, $y){ return $x && is_numeric($y); },
true);
The failings are that it won't break when it has found what it wants, so the functional suggestions above are not very efficient. You would need to write a function like this:
function array_find(array $array, $callback){
foreach ($array as $x){ //using iteration as PHP fails at recursion
if ( call_user_func($callback, array($x)) ){
return $x;
}
}
return false;
}
And use it like so
$isAllNumeric = array_find($arr, function($x){return !is_numeric($x);})) !== false;
i have two tiny but extremely useful functions in my "standard library"
function any($ary, $func) {
foreach($ary as $val)
if(call_user_func($func, $val)) return true;
return false;
}
function all($ary, $func) {
foreach($ary as $val)
if(!call_user_func($func, $val)) return false;
return true;
}
in your example
foreach ( $arrays as $arr )
echo all($arr, 'is_numeric') ? "ok" : "not ok";
A more elegant approach IMHO:
foreach ($arrays as $array)
{
if (array_product(array_map('is_numeric', $array)) == true)
{
echo "TRUE\n";
}
else
{
echo "FALSE\n";
}
}
This will return true if all the values are numeric and false if any of the values is not numeric.