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)
Related
How to add an element to an array using a key as ordinal element?
Before all, this is a theoretical question, and I'm looking for an answer instead of a way to reach the goal.
I've a function that generate a key, and I'was asking myself if there's a key to add to an array an element as ordinal element
$a=[];
$key=generateKey();
$a[$key]="pino";
var_export($a);
I was hoping this result:
array (
0 => 'pino'
)
A more advanced situation could be
array (
0 => 'a',
'7239ea2b5dc943f61f3c0a0276c20974' => 'b',
1 => 'c',
'c180aaadf5ab10fb3a733f43f3ffc4b3' => 'lino',
'48bb6e862e54f2a795ffc4e541caed4d' => 'gino',
2 => 'pino', // <- take 2 as index
)
EDIT
An hypothetic implementation of generateKey:
function generateKey($array){
$_rv=0;
foreach ($array as $k => $v){
if(is_numeric($k)==false){
continue;
}
$_rv=$k+1;
}
return $_rv;
}
I did not understand what was your real question... but as I have understood by your comment...
$a=[];
$key=generateKey();
to assign key to arry in php... below line is correct.
$a[$key]="pino";
If you want data in form of {key:value}...
var_export(json_encode($a));
If I understand correctly you just want to get highest numerical index of an array. You may try this:
$maxIdx = max(array_filter(array_keys($array), 'is_numeric')) ?: -1;
$array[$maxIdx + 1] = 'pino';
Looking the documentation of array-key-last I realized that the count function could achieve to generate a new numeric key without be cpu bounding:
$key=count($a);
$a[$key]="pino";
var_export($a);
Suppose I've got the following string:
) [6] => Array ( [2014-05-05 00:0] => My actual content
If I want to only be left with My actual content at the end, what is the best way to split the entire string?
Note: the words My actual content are and can change. I'm hoping to cut the string based on the second => string as this will be present at all times.
It seems you're just looking to find the first value of an array with keys you do not know. This is super simple:
Consider the following array:
$array = array(
'2014-05-22 13:36:00' => 'foo',
'raboof' => 'eh',
'qwerty' => 'value',
'8838277277272' => 'test'
);
Method #1:
Will reset the array pointer to the first element and return it.
Using reset:
var_dump( reset($array) ); //string(3) "foo"
DEMO
Method #2:
Will reset the entire array to use keys of 0, 1, 2, 3...etc. Useful if you need to get more than one value.
Using array_values:
$array = array_values($array);
var_dump( $array[0] ); //string(3) "foo"
DEMO
Method #2.5:
Will reset the entire array to use keys of 0, 1, 2, 3...etc and select the first one into the $content variable. Useful if you need to get more than one value into variables straight away.
Using list and array_values:
list( $content ) = array_values($array);
var_dump( $content ); //string(3) "foo"
DEMO
Method #3:
Arrays are iteratable, so you could iterate through it but break out immediately after the first value.
Using a foreach loop but break immediatly:
foreach ($array as $value) {
$content = $value;
break;
}
var_dump($content); //string(3) "foo"
DEMO
To Answer your question, on extracting from a string based on last 'needle'...
Okay, this is quite an arbitrary question, since it seems like you're showing us the results from a print_r(), and you could reference the array key to get the result.
However, you mentioned "... at the end", so I'm assuming My actual content is actually right at the end of your "String".
In which case there's a very simple solution. You could use: strrchr from the PHP manual - http://www.php.net/manual/en/function.strrchr.php.
So you're looking at this: strrchr($string, '=>');
Hope this answers your question. Advise otherwise if not please.
you have to use foreach loop in a foreach to get the multi dimentional array values.
foreach($value as $key){
foreach($key as $val){
echo $val;
}
}
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);
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";
}
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