My array looks like this:
array( '0|500|0.50', '501|1000|0.75' );
I am trying to run a search to get the KEY which has the searched value.
I made this function to search:
function cu_array_search($str,$array){
foreach($array as $key => $value) {
if(strstr($str,$value)) {
return true;
} else {
return false;
}
}
}
and using it like this when checking:
if (cu_array_search(500,$array) {
but it never return true, despite that 500 exists in first key in array .
How to resolve this?
Thanks
strpos will make you function return true even that's 0.5001 but not 500.
You should explode the value by |, then check whether the number in the array.
function cu_array_search($num, $array){
return count(array_filter($array, function ($var) use ($num) {
return in_array($num, explode('|', $var));
})) > 0;
}
The haystack is the first argument, not the second:
if(strstr($value,$str)) {
Additionally, strpos is faster at this, so you should use:
function cu_array_search($str,$array){
foreach($array as $key => $value) {
if(strpos($value,$str) !== false) {
return $key;
} else {
return false;
}
}
}
First, strstr parameters are wrong
Second, return false should be at the end of the loop.
Third, If you need KEY then You need to use return $key instead of return true
function cu_array_search($str,$array){
foreach($array as $key => $value) {
if(strstr($value, $str)) {
return $key;
}
}
return false;
}
This works fine
<?php
function cu_array_search($str, $array) {
foreach($array as $key => $value) {
$temp_array=explode('|', $value);
if (in_array($str, $temp_array))
return true;
}
return false;
}
$array = array( '0|500|0.50', '501|1000|0.75' );
if (cu_array_search(500, $array))
echo "success";
else
echo "failed" ;
?>
Related
I have an array, say
$updates = array();
$updates['U1'] = array('F1', 'F2', 'F5');
$updates['U2'] = array('F3');
$updates['U3'] = array('F3', 'F4');
I need search for a value say F5 so it should return the key U1.
And also if there is multiple occurrence of a value, should return the last key.
Eg. searching F3 should return U3 and not U2.
I have searched a lot and can't find a way. I am looking for a solution without using loops.
without using loop:
function findArrVal($arr = [], $param){
static $indx = 0;
if($indx == 0){
krsort($arr);
}
$keys = array_keys($arr);
$values = array_values($arr);
if( count($values) == $indx ){
return false;
} else if( is_array($values[$indx]) && in_array($param, $values[$indx])){
return $keys[$indx];
} else {
++$indx;
return findArrVal($arr, $param);
}
return FALSE;
}
using loop:
function findArrVal($arr = [], $param){
krsort($arr);
foreach($arr as $key => $ar){
if(is_array($ar) && in_array($param, $ar)){
return $key;
}
}
return FALSE;
}
findArrVal($updates,'F3');
krsort - sorts the array in reverse order. ( to find the value at first occurrence )
is_array to check if the child value is an array type.
in_array to find the item on the child array.
Maybe It's helpful for you.
function _getFindArrayKey(array $arr, $key)
{
if (array_key_exists($key, $arr)) {
return true;
}
// check arrays contained in this array
foreach ($arr as $element) {
if (is_array($element)) {
if (_getFindArrayKey($element, $key)) {
return true;
}
}
}
return false;
}
I have the following
Multidimensional array.
What I'm trying to do is to search for an IDITEM value and if it's found, return the value of the "PRECO" key.
I'm using the following function to check if the value exists and it works fine, but I can't find a way to get the "PRECO" value of the found IDITEM.
Function:
function search_array($needle, $haystack) {
if(in_array($needle, $haystack)) {
return true;
}
foreach($haystack as $element) {
if(is_array($element) && search_array($needle, $element))
return true;
}
return false;
}
Anyone can help me with that?
You can change the first if statement to return it instead of returning a boolean :
function search_array($needle, $haystack) {
if(in_array($needle, $haystack) && array_key_exists('PRECO', $haystack)) {
return $haystack['PRECO'];
}
foreach($haystack as $element) {
if(is_array($element))
{
$result = search_array($needle, $element);
if($result !== false)
return $result;
}
}
return false;
}
The easiest idea I can remember is converting that boolean search_array into a path creator, where it will return the path for the item, or false if it isn't found.
function get_array_path_to_needle($needle, array $haystack)
{
if(in_array($needle, $haystack))
{
return true;
}
foreach($haystack as $key => $element)
{
if(is_array($element) && ($path = get_array_path_to_needle($needle, $element)) !== false)
{
return $path === true ? $key : $key . '.' . $path;
}
}
return false;
}
Then, since you already have the path, then rerun the array to fetch the item
function get_array_value_from_path(array $path, array $haystack)
{
$current = $haystack;
foreach($path as $key)
{
if(is_array($current) && array_key_exists($key, $current))
{
$current = $current[$key];
}
else
{
return false;
}
}
return $current;
}
This wont get you the PRECO, but it will return the item (array) where id found the value you searched for.
So a simple usage would be:
$path = get_array_path_to_needle('000000000000001650', $data);
$item = get_array_value_from_path(explode('.', $path), $data);
// here you have full array for that item found
print_r($item);
// here you have your price
print_r($item['PRECO']);
Use a static variable to remember the status between multiple function calls, and also to store the desired PRECO value. It makes the function remember the value of the given variable ($needle_value in this example) between multiple calls.
So your search_array() function should be like this:
function search_array($needle, $haystack){
static $needle_value = null;
if($needle_value != null){
return $needle_value;
}
foreach($haystack as $key => $value){
if(is_array($value)){
search_array($needle, $value);
}else if($needle == $value){
$needle_value = $haystack['PRECO'];
break;
}
}
return $needle_value;
}
This function will finally return $needle_value, which is your desired PRECO value from the haystack.
The simplest way is to use a foreach loop twice. Check for the key and store the result into an array for later use.
Based on your array, the below
$search = '000000000000001650';
foreach($array as $element){
foreach ($element['ITEM'] as $item){
if (isset($item['IDITEM']) and $item['IDITEM'] == $search){
$results[] = $item['PRECO'];
}
}
}
print_r($results);
Will output
Array
(
[0] => 375
)
Here is the simple example with array:
// your array with two indexes
$yourArr = array(
0=>array(
'IDDEPARTAMENTO'=>'0000000001',
'DESCRDEPT'=>'Área',
'ITEM'=>
array(
array(
'SETID'=>'RX',
'IDITEM'=>'000000000000001367',
'DESCRITEM'=>'PISTA TESTE DRIV',
'PRECO'=>'1338.78'),
array(
'SETID'=>'RX',
'IDITEM'=>'000000000000001925',
'DESCRITEM'=>'PISTA TESTE DRIV2',
'PRECO'=>'916'),
)
),
1=>array(
'IDDEPARTAMENTO'=>'0000000010',
'DESCRDEPT'=>'Merch',
'ITEM'=>
array(
array(
'SETID'=>'RX',
'IDITEM'=>'000000000000002036',
'DESCRITEM'=>'PISTA TESTE DRIV23',
'PRECO'=>'200.78'),
array(
'SETID'=>'RX',
'IDITEM'=>'000000000000001608',
'DESCRITEM'=>'PISTA CRACHÁ DRIV4',
'PRECO'=>'44341'),
)
));
// solution
$newArr = array();
foreach ($yourArr as $value) {
foreach ($value as $key => $innerVal) {
if($key == 'ITEM'){
foreach ($innerVal as $key_inner => $keyinner) {
if(!empty($keyinner['IDITEM'])){
$newArr[$keyinner['IDITEM']] = $keyinner['PRECO'];
}
}
}
}
}
echo "<pre>";
print_r($newArr);
Result values with IDITEM:
Array
(
[000000000000001367] => 1338.78
[000000000000001925] => 916
[000000000000002036] => 200.78
[000000000000001608] => 44341
)
I'm having a trouble. I was trying to make it work for a long time, so I decided to ask for help here.
I have an with some arrays inside it:
$myarray = [
['string1','string2'],
['string3','string4'],
['string5',['string6','string7','string99']],
['string8','string9']
];
I am making a function that search for a s
function searchArray($array,$chave,$id) {
foreach ($array as $key) {
if (is_array($key)) {
if (($key[0] == $chave) && ($key[1] == $id)) {
break;
}
else {
searchArray($key,$chave,$id);
}
}
}
return $key;
}
$result = searchArray($myarray,'string6','string7');
print_r($result);
It was supposed to print ['string6','string7','string99']]
But it it printing the last "key" of the array: ['string8','string9']
The break is not working. After the break, it continue checking the next arrays.
with these modification it returns the expected values:
<?php
$myarray = [
['string1','string2'],
['string3','string4'],
['string5',['string6','string7','string99']],
['string8','string9']
];
function searchArray($array,$chave,$id) {
foreach ($array as $key) {
if (is_array($key)) {
if (($key[0] == $chave) && ($key[1] == $id)) {
return $key;
} else {
$res = searchArray($key,$chave,$id);
if($res !== false) {
return $res;
}
}
}
}
return false;
}
$result = searchArray($myarray,'string6','string7');
print_r($result);
the failure was to break on success. That makes no sense.
You need to return the value on success. If no success return false. Imagine it may happen that the searched values will not been found so it should return false.
I do not understand why "return" is not stopping the process in this function that I created to search a value on a multi_level array in PHP.
This is the code:
static function in_array_multi($needle, $haystack) {
foreach ($haystack as $item) {
if(is_array($item)){
in_array_multi($needle, $item);
}
else{
if ($item === $needle) {
return "ok";
}
}
}
return "nok";
}
I am using this array as exemple:
$arr = array(0 => array(id=>1,name=>"cat 1"),
1 => array(id=>2,name=>"cat 2"),
2 => array(id=>3,name=>array(id=>7,name=>"cat 7"))
);
And I am calling the function like this:
echo in_array_multi("cat 1",$arr);
It is returning "nok".
I am using xdebug to follow the process. It should stop the process on the second round.
Someone has any idea about what is happening?
Thanks
My comment was a bit careless. You would only want to return directly from the recursion if the recursion actually finds the value. You could do
function in_array_multi($needle, $haystack) {
foreach ($haystack as $item) {
if(is_array($item)){
if ('ok' === in_array_multi($needle, $item)) {
return 'ok';
}
}
elseif ($item === $needle) {
return "ok";
}
}
return "nok";
}
Because you make the return of function will stop the loop, you should collect it and return in the final.
Maybe you want this..
function array_multiple_search($array, $key, $value=null) {
$return = array();
if (is_array($array)) {
if (isset($array[$key])) {
if (is_null($value)) {
$return[] = $array;
} elseif ($array[$key] == $value) {
$return[] = $array;
}
}
foreach ($array as $subarray) {
$return = array_merge($return, array_multiple_search($subarray, $key, $value));
}
}
return $return;
}
param 1 is the target array
param 2 is the key you want to search of target array
param 3 is the value you want to search with the key of target array(can null)
This function will collect and return an array of qualified.
I know this question has been asked before but I haven't been able to get the provided solutions to work.
I'm trying to check if the words in an array match any of the words (or part of the words) in a provided string.
I currently have the following code, but it only works for the very first word in the array. The rest of them always return false.
"input" would be the "haystack" and "value" would be the "needle"
function check($array) {
global $input;
foreach ($array as $value) {
if (strpos($input, $value) !== false) {
// value is found
return true;
} else {
return false;
}
}
}
Example:
$input = "There are three";
if (check(array("one","two","three")) !== false) {
echo 'This is true!';
}
In the above, a string of "There is one" returns as true, but strings of "There are two" or "There are three" both return false.
If a solution that doesn't involve having to use regular expressions could be used, that would be great. Thanks!
The problem here is that check always returns after the first item in $array. If a match is found, it returns false, if not, it returns true. After that return statement, the function is done with and the rest of the items will not be checked.
function check($array) {
global $input;
foreach($array as $value) {
if(strpos($input, $value) !== false) {
return true;
}
}
return false;
}
The function above only returns true when a match is found, or false when it has gone through all the values in $array.
strpos(); is totally wrong here, you should simply try
if ($input == $value) {
// ...
}
and via
if ($input === $value) { // there are THREE of them: =
// ...
}
you can even check if the TYPE of the variable is the same (string, integer, ...)
a more professional solution would be
in_array();
which checks for the existance of the key or the value.
The problem here is that you're breaking out of the function w the return statement..so u always cut out after the first comparison.
you should use in_array() to compare the array values.
function check($array) {
global $input;
foreach ($array as $value) {
if (in_array($value,$input))
{
echo "Match found";
return true;
}
else
{
echo "Match not found";
return false;
}
}
}
You're returning on each iteration of $array, so it will only run once. You could use stristr or strstr to check if $value exists in $input.
Something like this:
function check($array) {
global $input;
foreach ($array as $value) {
if (stristr($input, $value)) {
return true;
}
}
return false;
}
This will then loop through each element of the array and return true if a match is found, if not, after finishing looping it will return false.
If you need to check if each individual item exists in $input you'd have to do something a little bit different, something like:
function check($array) {
global $input;
$returnArr = array();
foreach ($array as $value) {
$returnArr[$value] = (stristr($input, $value)) ? true : false;
}
return $returnArr;
}
echo '<pre>'; var_dump(check($array, $input)); echo '</pre>';
// outputs
array(3) {
["one"]=>
bool(false)
["two"]=>
bool(false)
["three"]=>
bool(true)
}
The reason your code doesnt work, is because you are looping through the array, but you are not saving the results you are getting, so only the last result "counts".
In the following code I passed the results to a variable called $output:
function check($array) {
global $input;
$output = false;
foreach ($array as $value) {
if (strpos($input, $value) != false) {
// value is found
$output = true;
}
}
return $output;
}
and you can use it like so:
$input = "There are two";
$arr = array("one","two","three");
if(check($arr)) echo 'this is true!';