how to get the numeric position of the array using php - 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;

Related

PHP - Get first and last key and value from array

From a given array (eg: $_SERVER), I need to get the first and last key and value. I was trying use array_shift to get first value and key but what I get is value.
Here is the $_SERVER array:
print_r($_SERVER, true))
And I tried with:
echo array_shift($_SERVER);
With PHP >= 7.3 you can get it fast, without modification of the array and without creating array copies:
$first_key = array_key_first($_SERVER);
$first_value = $_SERVER[$first_key];
$last_key = array_key_last($_SERVER);
$last_value = $_SERVER[$last_key];
See array_key_first and array_key_last.
It's not clear if you want the value, or the key. This is about as efficient as it gets, if memory usage is important.
If you want the key, use array_keys. If you want the value, just refer to it with the key you got from array_keys.
$count = count($_SERVER);
if ($count > 0) {
$keys = array_keys($_SERVER);
$firstKey = $keys[0];
$lastKey = $keys[$count - 1];
$firstValue = $array[$firstKey];
$lastValue = $array[$lastKey];
}
You can't use $count - 1 or 0 to get the first or last value in keyed arrays.
You can do a foreach loop, and break out after the first one:
foreach ( $_SERVER as $key => $value ) {
//Do stuff with $key and $value
break;
}
Plenty of other methods here. You can pick and choose your favorite flavor there.
Separate out keys and values in separate arrays, and extract first and last from them:
// Get all the keys in the array
$all_keys = array_keys($_SERVER);
// Get all the values in the array
$all_values = array_values($_SERVER);
// first key and value
$first_key = array_shift($all_keys);
$first_value = array_shift($all_values);
// last key and value (we dont care about the pointer for the temp created arrays)
$last_key = end($all_keys);
$last_value = end($all_values);
/* you can use reset function after end function call
if you worry about the pointer */
What about this:
$server = $_SERVER;
echo array_shift(array_values($server));
echo array_shift(array_keys($server));
reversed:
$reversed = array_reverse($server);
echo array_shift(array_values($reversed));
echo array_shift(array_keys($reversed));
I think array_slice() will do the trick for you.
<?php
$a = array_slice($_SERVER, 0, 1);
$b = array_slice($_SERVER, -1, 1, true);
//print_r($_SERVER);
print_r($a);
print_r($b);
?>
OUTPUT
Array ( [TERM] => xterm )
Array ( [argc] => 1 )
DEMO: https://3v4l.org/GhoFm

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!!

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

PHP: How do I check the contents of an array for my string?

I a string that is coming from my database table say $needle.
If te needle is not in my array, then I want to add it to my array.
If it IS in my array then so long as it is in only twice, then I still
want to add it to my array (so three times will be the maximum)
In order to check to see is if $needle is in my $haystack array, do I
need to loop through the array with strpos() or is there a quicker method ?
There are many needles in the table so I start by looping through
the select result.
This is the schematic of what I am trying to do...
$haystack = array();
while( $row = mysql_fetch_assoc($result)) {
$needle = $row['data'];
$num = no. of times $needle is in $haystack // $haystack is an array
if ($num < 3 ) {
$$haystack[] = $needle; // hopfully this adds the needle
}
} // end while. Get next needle.
Does anyone know how do I do this bit:
$num = no. of times $needle is in $haystack
thanks
You can use array_count_values() to first generate a map containing the frequency for each value, and then only increment the value if the value count in the map was < 3, for instance:
$original_values_count = array_count_values($values);
foreach ($values as $value)
if ($original_values_count[$value] < 3)
$values[] = $value;
As looping cannot be completely avoided, I'd say it's a good idea to opt for using a native PHP function in terms of speed, compared to looping all values manually.
Did you mean array_count_values() to return the occurrences of all the unique values?
<?php
$a=array("Cat","Dog","Horse","Dog");
print_r(array_count_values($a));
?>
The output of the code above will be:
Array (
[Cat] => 1,
[Dog] => 2,
[Horse] => 1
)
There is also array_map() function, which applies given function to every element of array.
Maybe something like the following? Just changing Miek's code a little.
$haystack_count = array_count_values($haystack);
if ($haystack_count[$needle] < 3)
$haystack[] = $needle;

Problem in array search

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);

Categories