There is an array:
$bounds = array([0]=>array('lower'=>2,'upper'=>5),
[1]=>array('lower'=>0,'upper'=>3));
and a variable:
$val = 4;
Is there any PHP function that can say whether $val belongs to any interval defined by 'lower' and 'upper' bounds in $bounds array? In this example 4 belongs to the 1st interval [2; 5]. So, the answer should be 'true'.
I don't think there is a built-in function to do this.
However, you can do it with a foreach statement:
function check_interval($bounds, $val) {
foreach ($bounds as $array) {
if($array['lower'] <= $val && $array['upper'] >= $val)
return true;
}
return false;
}
I'm not aware of any. You'll probably have to code it. Something like this will do:
function isFromInterval($bounds, $val) {
foreach ($bounds as $value) {
if ($val >= $value['lower'] && $val <= $value['upper']) {
return true;
}
}
return false;
}
No.
You would have to make a loop for the array like this
$val = 4;
$key_id = FALSE;
foreach($bounds as $key => $data){
if($val <= $data['upper'] AND $val >= $data['lower']){
$key_id = $key;
break;
}
}
if($key_id !== FALSE){
// found something
// $bounds[$key_id] is your result in the array
} else {
// found nothing
}
As a function
function find_range($bounds=array(), $val=0, $return_key=TRUE){
if(is_array($bounds) === FALSE){
$bounds = array();
}
if(is_numeric($val) === FALSE){
$val = 0;
}
if(is_bool($return_key) === FALSE){
$return_key = TRUE;
}
$key_id = FALSE;
foreach($bounds as $key => $data){
if($val < $data['upper'] AND $val > $data['lower']){
$key_id = $key;
break;
}
}
if($key_id !== FALSE){
return ($return_key === TRUE ? $key_id : TRUE);
} else {
return FALSE;
}
}
No, but you can do:
$bounds = array(3=>array('lower'=>2,'upper'=>5),
4=>array('lower'=>0,'upper'=>3));
$val = 4;
foreach($bounds as $num => $bound){
if(max($bound) >= $val && $val >= min($bound)){
echo $num;
}
}
Related
The problem lies in the fact that I have to type the full name for the search phrase.
Maybe can I use strpos in this?
if ($filter && $searchOption && $searchPhrase && $sortField == "createDate" && $order == "asc") {
usort($caseList, function ($a, $b) {
/* #var $a CMCase */
/* #var $b CMCase */
$time1 = strtotime($a->createDate);
$time2 = strtotime($b->createDate);
return $time1 > $time2;
});
} else if ($filter && $searchOption == "search_customer" && $searchPhrase && $sortField && $order) {
$list = $caseList;
$caseList = array();
foreach ($list as $case) {
if ($case->customerName == $searchPhrase) {
$caseList[] = $case;
}
}
}
You can rewrite your code like this:
$result = array_filter($caseList, function($case) use ($searchPhrase){
return stripos($case->customerName, $searchPhrase) !== FALSE;
})
But you still need to be more concrete.
! I used stripos to case insensitive search. See the manual
P.S. Just try this instead of your code:
if ($searchOption == "search_customer" && $searchPhrase) use ($searchPhrase) {
$list = array_filter($caseList,function($case) {
return stripos($case->customerName, $searchPhrase) !== false;
});
}
This is my solution:
// Searching
{
if ($filter && $searchOption == "search_customer" && $searchPhrase && $sortField && $order) {
$list = array();
foreach ($caseList as $case) {
if (stripos($case->customerName,$searchPhrase)!== FALSE) {
$list[] = $case;
}
}
$caseList = $list;
} else if ($filter && $searchOption == "search_request" && $searchPhrase && $sortField && $order) {
$list = array();
foreach ($caseList as $case) {
if (stripos($case->identifier,$searchPhrase)!== FALSE) {
$list[] = $case;
}
}
$caseList = $list;
}
}
I am working with php 5.1 and need to implement JSON_PRESERVE_ZERO_FRACTION and JSON_PARTIAL_OUTPUT_ON_ERROR to encode array as json in this function:
function _json_encode($val, $optios=0)
{
if (is_string($val)) return '"'.addslashes($val).'"';
if (is_numeric($val)) return $val;
if ($val === null) return 'null';
if ($val === true) return 'true';
if ($val === false) return 'false';
$assoc = false;
$i = 0;
foreach ($val as $k=>$v){
if ($k !== $i++){
$assoc = true;
break;
}
}
$res = array();
foreach ($val as $k=>$v){
$v = _json_encode($v);
if ($assoc){
$k = '"'.addslashes($k).'"';
$v = $k.':'.$v;
}
$res[] = $v;
}
$res = implode(',', $res);
return ($assoc)? '{'.$res.'}' : '['.$res.']';
}
I am not getting how to add those constants?
Having some issues parsing my multidimensional php array and removing duplicates. I've spent a good four hours trying to figure out what I'm doing wrong with no luck. If someone could help me out that would wonderful.
Format of multidimensional array:
Array(Array("id"=>?, "step_num"=>?, "desc"=>?))
Example data set:
Array(
[0]=> Array([id]=>1, [step_count]=>1, [desc]=>"Something"),
[1]=> Array([id]=>2, [step_count]=>1, [desc]=>"Something New"),
[2]=> Array([id]=>3, [step_count]=>1, [desc]=>"Something Newest")
)
Here's how I am trying to only have the step_count with the most recent desc by comparing id values: ($subStepsFound has the same format as the above array and $results is an empty array to begin with)
foreach($subStepsFound AS $step){
$found = false;
$removeEntry = false;
$index = 0;
foreach($results AS $key=>$result){
if($step['step_count'] == $result['step_count']){
$found = true;
if($step['id'] > $result['id']){
$removeEntry = true;
}
}
if($removeEntry === true){
$index = $key;
}
}
if($removeEntry === true){
//unset($results[$index]);
$results[$index] = $step;
}
if($found === false){
$results[] = $step;
}
}
Expected output of the resulting array:
Array(
[0]=> Array([id]=>4, [step_count]=>1, [desc]=>"Something Newest")
)
See 1., 2., 3. in comments:
foreach($subStepsFound AS $step){
$found = false;
$removeEntry = false;
$index = 0;
foreach($results AS $key=>$result){
if($step['step_count'] == $result['step_count']){
$found = true;
if($step['id'] > $result['id']){
$removeEntry = true;
}
}
if($removeEntry === true){
$results[$key] = $step; // 2. UP TO HERE
$removeEntry = false; // 3. RESET $removeEntry
}
}
/*
if($removeEntry === true){
//unset($results[$index]);
$results[$index] = $step; // 1. MOVE THIS...
}
*/
if($found === false){
$results[] = $step;
}
}
print_r($results);
Online example: http://sandbox.onlinephpfunctions.com/code/1db78a8c08cbee9d04fe1ca47a6ea359cacdd9e9
/*super_unique: Removes the duplicate sub-steps found*/
function super_unique($array,$key){
$temp_array = array();
foreach ($array as &$v) {
if (!isset($temp_array[$v[$key]])) $temp_array[$v[$key]] =& $v;
}
$array = array_values($temp_array);
return $array;
}
$results = super_unique($subStepsFound, 'step_count');
How to know if a given string starts with a defied set of words?
$allowed = array("foo", "bar");
pseudocode:
$boolean = somefunction($allowed,'food');
$boolean should be TRUE
function doesStringStartWith($string, $startWithOptions)
{
foreach($startWithOptions as $option)
{
if(substr($string, 0, strlen($option)) == $option) // comment this for case-insenstive
// uncomment this for case-insenstive: if(strtolower(substr($string, 0, strlen($option))) == strtolower($option))
{
return true;
}
}
return false;
}
$result = doesStringStartWith('food', array('foo', 'bar'));
function somefunction($allowed, $word) {
$result = array_filter(
$allowed,
function ($value) use ($word) {
return strpos($word, $value) === 0;
}
);
return (boolean) count($result);
}
$boolean = somefunction($allowed,'food');
If you know that all of your prefixes are the same length you could do this:
if ( in_array( substr($input,0,3), $allowed ) {
// your code
}
I came up with the following function:
function testPos($allowed,$s) {
$a = 0;
while($a < count($allowed)) {
if(strpos($s,$allowed[$a]) === 0) {
return true;
}
$a++;
}
}
Now you can try:
$allowed = array('foo','bar');
echo testPos($allowed,'food');
I want to remove some duplicate values on an array, but there is a condition that the script has to ignore the array that contains a specific word.
Below code is adapted from PHP: in_array.
$array = array( 'STK0000100001',
'STK0000100002',
'STK0000100001', //--> This should be remove
'STK0000100001-XXXX', //--> This should be ignored
'STK0000100001-XXXX' ); //--> This should be ignored
$ignore_values = array('-XXXX');
if(make_unique($array, $ignore_values) > 0) {
//ERROR HERE
}
The function to make the array unique is:
function make_unique($array, $ignore) {
$i = 0;
while($values = each($array)) {
if(!in_array($values[1], $ignore)) {
$dupes = array_keys($array, $values[1]);
unset($dupes[0]);
foreach($dupes as $rmv) {
$i++;
}
}
}
return $i;
}
I have tried to use if(!in_array(str_split($values[1]), $ignore)) ... but it just the same.
The array should become like:
STK0000100001
STK0000100002
STK0000100001-XXXX
STK0000100001-XXXX
How to do that?
Try this one, just remove the print_r(); inside the function when using in production
if(make_unique($array, $ignore_values) > 0) {
//ERROR HERE
}
function make_unique($array, $ignore) {
$array_hold = $array;
$ignore_val = array();
$i = 0;
foreach($array as $arr) {
foreach($ignore as $ign) {
if(strpos($arr, $ign)) {
array_push( $ignore_val, $arr);
unset($array_hold[$i]);
break;
}
}
$i++;
}
$unique_one = (array_unique($array_hold));
$unique_one = array_merge($unique_one,$ignore_val);
print_r($unique_one);
return count($array) - count($unique_one);
}
This should work for >= PHP 5.3.
$res = array_reduce($array, function ($res, $val) use ($ignore_values) {
$can_ignore = false;
foreach ($ignore_values as $ignore_val) {
if (substr($val, 0 - strlen($ignore_val)) == $ignore_val) {
$can_ignore = true;
break;
}
}
if ( $can_ignore || ! in_array($val, $res)) {
$res[] = $val;
}
return $res;
}, array()
);
Otherwise
$num_of_duplicates = 0;
$res = array();
foreach ($array as $val) {
$can_ignore = false;
foreach ($ignore_values as $ignore_val) {
if (substr($val, 0 - strlen($ignore_val)) == $ignore_val) {
$num_of_duplicates++;
$can_ignore = true;
break;
}
}
if ( $can_ignore || ! in_array($val, $res)) {
$res[] = $val;
}
}
Edit: Added duplicate count to the second snippet.