Problem in array search - php

I am trying to find values inside an array. This array always starts with 0.
unfortunately array_search start searching with the array element 1.
So the first element is always overlooked.
How could I "shift" this array to start with 1, or make array-search start with 0? The array comes out of an XML web service, so I can not rally modify the results.

array_search does not start searching at index 1. Try this example:
<?php
$array = array(0 => 'blue', 1 => 'red', 2 => 'green', 3 => 'red');
$key = array_search('blue', $array); // $key = 0
?>
Whatever the problem is with your code, it's not that it's first element is index 0.
It's more likely that you're use == instead of === to check the return value. If array_search returns 0, indicating the first element, the following code will not work:
// doesn't work when element 0 is matched!
if (false == array_search(...)) { ... }
Instead, you must check using ===, which compares both value and type
// works, even when element 0 is matched
if (false === array_search(...)) { ... }

See the manual, it might help you:
http://www.php.net/manual/en/function.array-search.php
If what you're trying to do is use increase the key by one, you can do:
function my_array_search($needle, $haystack, $strict=false) {
$key = array_search($needle, $haystack, $strict);
if (is_integer($key)) $key++;
return $key;
}
my_array_search($xml_service_array);

Related

PHP: counting all the items of a multilevel array containing a given parameter and a given value

I'm trying to build a function to count all the items of an array containing a given parameter, but, if the parameter is not given when calling the function, the function should count all the items. Parameters are passed with an array $params: This is what I have done so far:
function myfunction($params){
global $myArray;
if ( !isset($params[0]) ){ $params[0] = ???????? } // I need a wildcard here, so that, if the parameter is not given, the condition will be true by default
if ( !isset($params[1]) ){ $params[1] = ???????? } // I need a wildcard here, so that, if the parameter is not given, the condition will be true by default
....etc......
foreach($myArray as $item){
if ($item[0] == $params[0]){ // this condition should be true if parameter is not given
if ($item[1] == $params[1]){// this condition should be true if parameter is not given
$count += $item
}
}
}
return $count;
}
I would like:
myfunction(); //counts everything
myfunction( array ('0' => 'banana') ); //counts only $myArray['0'] = banana
myfunction( array ('0' => 'apple', '1' => 'eggs') ); //counts only $myArray['0'] = apples and $myArray['1'] = eggs
I have several $params[keys] to check this way.
I guess, if I should assign a default value to params[key] (like a wildcard) , so that, if it is not given, the function will take all the $item. I mean something that $item[0] will always be (==) equal to. Thanks. [See my answer for solution]
The way your function is declared, you have to pass a parameter. What you want to do is have a default value so that your code inside the function can detect that:
function myfunction($params=NULL)
{
global $myArray;
if (empty($params))
{
// count everything
}
else
{
// count what's listed in the $params array
}
}
EDIT
If I read your comments correctly, $myArray looks something like this:
$myArray=array
(
'apple'=>3, // 3 apples
'orange'=>4, // 4 oranges
'banana'=>2, // 2 bananas
'eggs'=>12, // 12 eggs
'coconut'=>1, // 1 coconut
);
Assuming that's true, what you want is
function myfunction($params=NULL)
{
global $myArray;
$count=0;
if (empty($params)) // count everything
{
foreach ($myArray as $num) // keys are ignored
$count += $num;
}
else if (!is_array($params)) // sanity check
{
// display an error, write to error_log(), etc. as appropriate
}
else // count what's listed in the $params array
{
foreach ($params as $key) // check each item listed in $params
if (isset($myArray[$key])) // insure request in $myArray
$count += $myArray[$key]; // add item's count to total
}
return $count;
}
This will give you
myfunction(); // returns 22
myfunction(array('banana')); // returns 2
myfunction(array('apple','eggs')); // returns 15
myfunction(array('tomatoes')); // returns 0 - not in $myArray
If this isn't the result you're looking for, you need to rewrite your question.
EDIT # 2
Note that because arrays specified without explicit keys are keyed numerically in the order the elements are listed, the function calls I showed above are exactly equivalent to these:
myfunction(); // returns 22
myfunction(array(0=>'banana')); // returns 2
myfunction(array(0=>'apple',1=>'eggs')); // returns 15
myfunction(array(0=>'tomatoes')); // returns 0 - not in $myArray
However, the calls are not equivalent to these:
myfunction(); // returns 22
myfunction(array('0'=>'banana')); // returns 2
myfunction(array('0'=>'apple','1'=>'eggs')); // returns 15
myfunction(array('0'=>'tomatoes')); // returns 0
In this case, explicit string keys are specified for the array, and while the strings' values will evaluate the same as the numerical indices under most circumstances, string indices are not the same as numerical ones.
The code you proposed in your answer has a few errors:
foreach($myArray as $item)
{
foreach ($params as $key => $value)
{
if ( isset($params[$key]) && $params[$key] == $item[$key] )
{
$count += $item
}
}
}
First, isset($params[$key]) will always evaluate to TRUE by the nature or arrays and foreach. Second, because of your outer foreach loop, if your $myArray is structured as I illustrated above, calling myfunction(array('apple')) will result in $params[$key] == $item[$key] making these tests because $key is 0:
'apple' == 'apple'[0] // testing 'apple' == 'a'
'apple' == 'orange'[0] // testing 'apple' == 'o'
'apple' == 'banana'[0] // testing 'apple' == 'b'
'apple' == 'eggs'[0] // testing 'apple' == 'e'
'apple' == 'coconut'[0] // testing 'apple' == 'c'
As you can see, this will not produce the expected results.
The third problem with your code is you don't have a semicolon at the end of the $count += $item line, so I'm guessing you didn't try running this code before proposing it as an answer.
EDIT # 3
Since your original question isn't terribly clear, it occurred to me that maybe what you're trying to do is count the number of types of things in $myArray rather than to get a total of the number of items in each requested category. In that case, the last branch of myfunction() is even simpler:
else // count what's listed in the $params array
{
foreach ($params as $key) // check each item listed in $params
if (isset($myArray[$key])) // insure request in $myArray
$count++; // add the item to the total
}
With the sample $myArray I illustrated, the above change will give you
myfunction(); // returns 5
myfunction(array('banana')); // returns 1
myfunction(array('apple','eggs')); // returns 2
myfunction(array('tomatoes')); // returns 0 - not in $myArray
Again, if neither of these results are what you're looking for, you need to rewrite your question and include a sample of $myArray.
MY SOLUTION
(Not extensively tested, but works so far)
Following #FKEinternet answer, this is the solution that works for me: obviously the $params should use the same keys of $item. So, foreach iteration if parameter['mykey'] is given when calling the function and its value is equal to item['mykey'], count the iteration and $count grows of +1
function myfunction($params=NULL){
global $myArray;
foreach($myArray as $item){
foreach ($params as $key => $value){
if ( isset($params[$key]) && $params[$key] == $item[$key] ){
$count += $item;
}
}
}
return $count;
}
Thanks everybody for all inputs!!

how to get the numeric position of the array using php

i want to get the exact numeric position of the value in the array
array value:
$val = array('banana' , 'second' , 'apple');
when user search for the value apple
it will display
3
because it's the 3rd element
and when the user search for banana
it will display
1
Using array_search() like so:
$num = array_search('banana', $array) + 1;
$keys= array_keys($val, "apple")
Will return an array with the value 2 (all the indexes of the array that have the value "apple").
then you just have to get the first element of that array and add 1
$numericPosition = current($keys)
If $keys is empty, that is, "apple" doesnt exist in array, then $numericPosition === false, otherwise add 1. This ensures you can actually detect when a value doesnt exist, if you just add 1 to current($keys) any value not in the array will be at position 1.
Edit: array_search of the other answer will return only the 1st key of a given value, so it may match your needs better, just make sure you check for false before you add 1.
There is no other way (contrary to what other answers will suggest) than going through the array and checking. Any other solution will be a hack depending on the specific shape of your array (values or keys).
$search = "banana";
$index = 1;
foreach ($val as $v) {
if ($v === $search) break;
$index++;
}
echo "$search is number: $index ";
$word = 'banana';
$position = array_search($word, $val) + 1;

Finding the Index while searching from an Array using in_array in PHP

My aim is to find out what the operator is, and where it was in the original $operatorArray (which contains the various operators such as "+", "-" etc... )
So I have managed to check when $operator matches with another operator in my existing $operatorArray, however I need to know where in $operatorArray it is found.
foreach ($_SESSION['explodedQ'] as $operator){ //search through the user input for the operator.
if (in_array("$operator", $operatorArray)) { //if the operator that we found is in the array, then tell us what it is
print_r("$operator"); //prints the operator found
print_r("$positionNumber"); //prints where the operator is
} //if operator
else{
$positionNumber++; //The variable which keeps count on where the array is searching.
}
I've tried Google/Stack searching, but the thing is, I don't actually know what to Google search. I've searched for things like "find index from in_array" etc... and I can't see how to do it. If you could provide me with a simple way to understand how to achieve this, I would be greatful. Thanks for your time.
array_search will do what you are looking for
Taken straight from the PHP manual:
array_search() - Searches the array for a given value and returns the corresponding key if successful
If you're searching a non-associative array, it returns the corresponding key, which is the index you're looking for. For non-consecutively indexed arrays (i.e. array(1 => 'Foo', 3 => 'Bar', ...)) you can use the result of array_values() and search in it.
You might want to give this a try
foreach($_SESSION['explodedQ'] as $index => $operator) { /* your stuff */ }
That way you can print the $index as soon as your in_array() hits the right $operator.
i think you need array_search()
$array = array(0 => 'blue', 1 => 'red', 2 => 'green', 3 => 'red');
$key = array_search('green', $array); // $key = 2;
$key = array_search('red', $array); // $key = 1;
Use:
$key = array_search($operator, $array);

selecting an array key based on partial string

I have an array and in that array I have an array key that looks like, show_me_160 this array key may change a little, so sometimes the page may load and the array key maybe show_me_120, I want to now is possible to just string match the array key up until the last _ so that I can check what the value is after the last underscore?
one solution i can think of:
foreach($myarray as $key=>$value){
if("show_me_" == substr($key,0,8)){
$number = substr($key,strrpos($key,'_'));
// do whatever you need to with $number...
}
}
I ran into a similar problem recently. This is what I came up with:
$value = $my_array[current(preg_grep('/^show_me_/', array_keys($my_array)))];
you would have to iterate over your array to check each key separately, since you don't have the possibility to query the array directly (I'm assuming the array also holds totally unrelated keys, but you can skip the if part if that's not the case):
foreach($array as $k => $v)
{
if (strpos($k, 'show_me_') !== false)
{
$number = substr($k, strrpos($k, '_'));
}
}
However, this sounds like a very strange way of storing data, and if I were you, I'd check if there's not an other way (more efficient) of passing data around in your application ;)
to search for certain string in array keys you can use array_filter(); see docs
// the array you'll search in
$array = ["search_1"=>"value1","search_2"=>"value2","not_search"=>"value3"];
// filter the array and assign the returned array to variable
$foo = array_filter(
// the array you wanna search in
$array,
// callback function to search for certain sting
function ($key){
return(strpos($key,'search_') !== false);
},
// flag to let the array_filter(); know that you deal with array keys
ARRAY_FILTER_USE_KEY
);
// print out the returned array
print_r($foo);
if you search in the array values you can use the flag 0 or leave the flag empty
$foo = array_filter(
// the array you wanna search in
$array,
// callback function to search for certain sting
function ($value){
return(strpos($value,'value') !== false);
},
// flag to let the array_filter(); know that you deal with array value
0
);
or
$foo = array_filter(
// the array you wanna search in
$array,
// callback function to search for certain sting
function ($value){
return(strpos($value,'value') !== false);
}
);
if you search in the array values and array keys you can use the flag ARRAY_FILTER_USE_BOTH
$foo = array_filter(
// the array you wanna search in
$array,
// callback function to search for certain sting
function ($value, $key){
return(strpos($key,'search_') !== false or strpos($value,'value') !== false);
},
ARRAY_FILTER_USE_BOTH
);
in case you'll search for both you have to pass 2 arguments to the callback function
You can also use a preg_match based solution:
foreach($array as $str) {
if(preg_match('/^show_me_(\d+)$/',$str,$m)) {
echo "Array element ",$str," matched and number = ",$m[1],"\n";
}
}
filter_array($array,function ($var){return(strpos($var,'searched_word')!==FALSE);},);
return array 'searched_key' => 'value assigned to the key'
foreach($myarray as $key=>$value)
if(count(explode('show_me_',$event_key)) > 1){
//if array key contains show_me_
}
More information (example):
if array key contain 'show_me_'
$example = explode('show_me_','show_me_120');
print_r($example)
Array ( [0] => [1] => 120 )
print_r(count($example))
2
print_r($example[1])
120

Search an array for a matching string

I am looking for away to check if a string exists as an array value in an array is that possible and how would I do it with PHP?
If you simply want to know if it exists, use in_array(), e.g.:
$exists = in_array("needle", $haystack);
If you want to know its corresponding key, use array_search(), e.g.:
$key = array_search("needle", $haystack);
// will return key for found value, or FALSE if not found
You can use PHP's in_array function to see if it exists, or array_search to see where it is.
Example:
$a = array('a'=>'dog', 'b'=>'fish');
in_array('dog', $a); //true
in_array('cat', $a); //false
array_search('dog', $a); //'a'
array_search('cat', $a); //false
Php inArray()
Incidentally, although you probably should use either in_array or array_search like these fine gentlemen suggest, just so you know how to do a manual search in case you ever need to do one, you can also do this:
<?php
// $arr is the array to be searched, $needle the string to find.
// $found is true if the string is found, false otherwise.
$found = false;
foreach($arr as $key => $value) {
if($value == $needle) {
$found = true;
break;
}
}
?>
I know it seems silly to do a manual search to find a string - and it is - but you may one day wish to do more complicated things with arrays, so it's good to know how to actually get at each $key-$value pair.
Here you go:
http://www.php.net/manual/en/function.array-search.php
The array_search function does exactly what you want.
$index = array_search("string to search for", $array);
Say we have this array:
<?php
$array = array(
1 => 'foo',
2 => 'bar',
3 => 'baz',
);
?>
If you want to check if the element 'foo' is in the array, you would do this
<?php
if(in_array('foo', $array)) {
// in array...
}else{
// not in array...
}
?>
If you want to get the array index of 'foo', you would do this:
<?php
$key = array_search('foo', $array);
?>
Also, a simple rule for the order of the arguments in these functions is: "needle, then haystack"; what you're looking for should be first, and what you're looking in second.

Categories