php compare array keys, not values - php

I am successfully using the array_key_exists(), as described by php.net
Example:
<?php
$search_array = array('first' => 1, 'second' => 4);
if (array_key_exists('first', $search_array)) {
echo "The 'first' element is in the array";
}
?>
But, take out the values, and it doesn't work.
<?php
$search_array = array('first', 'second');
if (array_key_exists('first', $search_array)) {
echo "The 'first' element is in the array";
}
?>
Not sure how to only compare 2 arrays by their keys only.

The first example is an associative array: keys with values assigned. The second example is just a prettier way of saying:
array(0 => 'first', 1 => 'second')
For the second, you would need to use in_array. You shouldn't check for the presence of a key, which array_key_exists does, but rather the presence of a value, which in_array does.
if(in_array('first', $array))

In PHP, each element in a array has two parts: the key and the value.
Unless you manually say what keys you want attached to each value, PHP gives each element a numerical index starting at 0, incrementing by 1.
So the difference between
array('first','second')
and
array('first'=>1,'second'=>4)
is that the first doesn't have user-defined keys. (It actually has the keys 0 and 1)
If you were to do print_r() on the first, it would say something like
Array {
[0] => "first",
[1] => "second"
}
whereas the second would look like
Array {
["first"] => 1,
["second"] => 2
}
So, to check if the key "first" exists, you would use
array_key_exists('first',$search_array);
to check if the the value "first" exists, you would use
in_array('first',$search_array);

in the second example, you didn't assign array keys - you just set up a basic "list" of objects
use in_array("first", $search_array); to check if a value is in a regular array

In your second example the keys are numeric your $search_array actually looks like this:
array(0=>'first', 1=>'second');
so they key 'first' doesnt exist, the value 'first' does. so
in_array('first', $search_array);
is the function you would want to use.

In PHP, if you are not giving key to array element they take default key value.Here you arrray will be internally as bellow
$search_array = array(0=>'first', 1=>'second');
Anyway you can still fix this problem by using the array_flip function as below.
$search_array = array('first', 'second');
if (array_key_exists('first', array_flip($search_array))) {
echo "The 'first' element is in the array";
}

Related

Can Indexed Arrays be used as associative arrays?

I know that in PHP an indexed array that looks like:
$array = ("hello", "world")
is the same as an associative array that looks like:
$array = (0 => "hello", 1 => "world");
so my question is if code like this is valid :
$hello = $array[$array["hello"]];
my thinking is that it translates to
$hello = $array[0]
, which will equal
$hello = "hello"
. In other words, will
$array["hello"]
equal 0?
No, you cannot fetch a key of some array element by its value right away... unless you switch keys and values with array_flip:
$arr = array('hello', 'world');
$arr = array_flip($arr);
print $arr['hello']; // 0
Let's walk through the thinking:
$array = ("hello", "world") // This is implicitly indexed by integer.
is the same as:
$array = (0 => "hello", 1 => "world"); // Explicit indexing.
You can verify by doing print_r($array); In either case, the output would show an indexed array. PHP arrays are all associative. Even if you did not specify a key, the values in an array are ordered by integer index numbers.
Now let's take a look at:
so my question is if code like this is valid :
$hello = $array[$array["hello"]];
This is where the code will break. Why?
$array["hello"] is not a valid value. What this is referencing is "the value of the array's list at index "hello".
However, array("hello", "world") does not have an index key of "hello". Rather, it has a value "hello" which has implicitly the key index 0.
Make sure to read up on PHP arrays and understand that:
PHP arrays are all associative; keys can be strings, or if not explicitly set, will be integers.
Associative arrays are in the form of key => value pairs. If you have a key, you can find the value associated with it.
When trying to get a value from a PHP array, the syntax is: $array['key'] or in the case of multidimensionals $array['firstlevelkey']['secondlevelkey'] etc. The value that gets returned would be the value of the key => value pair at that particular key.
I hope this is helpful!
No, since "hello" is not a valid key in $array.
You can check if a key exist using array_key_exists(key,*array*)

associative to numeric array in PHP

I have an associative array, which keys I want to use in numbers. What I mean: The array is kinda like this:
$countries = array
"AD" => array("AND", "Andorra"),
"BG" => array("BGR", "Bulgaria")
);
Obviously AD is 0 and BG is 1, but when I print $countries[1] it doesn't display even "Array".
When I print $countries[1][0] it also doesn't display anything. I have the number of the key, but I shouldn't use the associative key.
Perfect use case for array_values:
$countries = array_values($countries);
Then you can retrieve the values by their index:
$countries[0][0]; // "AND"
$countries[0][1]; // "Andorra"
$countries[1][0]; // "BGR"
$countries[1][1]; // "Bulgaria"
array_keys() will give you the array's keys. array_values() will give you the array's values. Both will be indexed numerically.
you might convert it into a numeric array:
$countries = array(
"AD" => array("AND", "Andorra"),
"BG" => array("BGR", "Bulgaria")
);
$con=array();
$i=0;
foreach($countries as $key => $value){
$con[$i]=$value;
$i++;
}
echo $con[1][1];
//the result is Bulgaria
There are a couple of workarounds to get what you want. Besides crafting a secondary key-map array, injecting references, or an ArrayAccess abomination that holds numeric and associative keys at the same time, you could also use this:
print current(array_slice( current(array_slice($countries, 1)), 0));
That's the fugly workaround to $countries[1][0]. Note that array keys appear to appear in the same order still; bemusing.

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

How to get the position of a key within an array

Ok, so I need to grab the position of 'blah' within this array (position will not always be the same). For example:
$array = (
'a' => $some_content,
'b' => $more_content,
'c' => array($content),
'blah' => array($stuff),
'd' => $info,
'e' => $more_info,
);
So, I would like to be able to return the number of where the 'blah' key is located at within the array. In this scenario, it should return 3. How can I do this quickly? And without affecting the $array array at all.
$i = array_search('blah', array_keys($array));
If you know the key exists:
PHP 5.4 (Demo):
echo array_flip(array_keys($array))['blah'];
PHP 5.3:
$keys = array_flip(array_keys($array));
echo $keys['blah'];
If you don't know the key exists, you can check with isset:
$keys = array_flip(array_keys($array));
echo isset($keys['blah']) ? $keys['blah'] : 'not found' ;
This is merely like array_search but makes use of the map that exists already inside any array. I can't say if it's really better than array_search, this might depend on the scenario, so just another alternative.
$keys=array_keys($array); will give you an array containing the keys of $array
So, array_search('blah', $keys); will give you the index of blah in $keys and therefore, $array
User array_search (doc). Namely, `$index = array_search('blah', $array)

How do I move an array element with a known key to the end of an array in PHP?

Having a brain freeze over a fairly trivial problem. If I start with an array like this:
$my_array = array(
'monkey' => array(...),
'giraffe' => array(...),
'lion' => array(...)
);
...and new elements might get added with different keys but always an array value. Now I can be sure the first element is always going to have the key 'monkey' but I can't be sure of any of the other keys.
When I've finished filling the array I want to move the known element 'monkey' to the end of the array without disturbing the order of the other elements. What is the most efficient way to do this?
Every way I can think of seems a bit clunky and I feel like I'm missing something obvious.
The only way I can think to do this is to remove it then add it:
$v = $my_array['monkey'];
unset($my_array['monkey']);
$my_array['monkey'] = $v;
array_shift is probably less efficient than unsetting the index, but it works:
$my_array = array('monkey' => 1, 'giraffe' => 2, 'lion' => 3);
$my_array['monkey'] = array_shift($my_array);
print_r($my_array);
Another alternative is with a callback and uksort:
uksort($my_array, create_function('$x,$y','return ($y === "monkey") ? -1 : 1;'));
You will want to use a proper lambda if you are using PHP5.3+ or just define the function as a global function regularly.
I really like #Gordon's answer for its elegance as a one liner, but it only works if the targeted key exists in the first element of the array. Here's another one-liner that will work for a key in any position:
$arr = ['monkey' => 1, 'giraffe' => 2, 'lion' => 3];
$arr += array_splice($arr, array_search('giraffe', array_keys($arr)), 1);
Demo
Beware, this fails with numeric keys because of the way that the array union operator (+=) works with numeric keys (Demo).
Also, this snippet assumes that the targeted key is guaranteed to exist in the array. If the targeted key does not exist, then the result will incorrectly move the first element to the end because array_search() will return false which will be coalesced to 0 by array_splice() (Demo).
You can implement some basic calculus and get a universal function for moving array element from one position to the other.
For PHP it looks like this:
function magicFunction ($targetArray, $indexFrom, $indexTo) {
$targetElement = $targetArray[$indexFrom];
$magicIncrement = ($indexTo - $indexFrom) / abs ($indexTo - $indexFrom);
for ($Element = $indexFrom; $Element != $indexTo; $Element += $magicIncrement){
$targetArray[$Element] = $targetArray[$Element + $magicIncrement];
}
$targetArray[$indexTo] = $targetElement;
}
Check out "moving array elements" at "gloommatter" for detailed explanation.
http://www.gloommatter.com/DDesign/programming/moving-any-array-elements-universal-function.html

Categories