I have a multidimensional array and would like to call the key and the value separately, of individual levels inside the array.
Now with a normal array, I can do this by writing:
$example = array('one', 'two', 'three');
echo $example[0];
and this will return: one
However, when I try to do this with a multidimensional array like so:
$example = array(
'optionone' => array('one', 'two', 'three'),
'optiontwo' => array('a','b','c'),
'optionthree' => array(1,2,3)
);
echo $example[0];
echo $example[0][0];
Instead of echoing 'optionone' followed by 'one' I get nothing returned, and no error code.
When trying to see why this is happening by using:
var_dump($example[0)];
or
var_dump($example[0][0]);
NULL is returned.
I would really appreciate if someone could tell me how to correctly get/echo/call 'optionone' to return from the array as a string: 'optionone' without writing the name and how can I call the value 'one' without writing:
$example['optionone'][0];
I'm trying to create something where it doesn't know the key name, so it rather is going by the position of the keys but i would like to be able to return the key names at different points in the program but I can't seem to figure out how to do this.
This should work for you:
Just get your associative keys into an array with array_keys(), so you can access them as a 0-based indexed array, e.g.
So with array_keys($example) you end up with the following array:
Array
(
[0] => optionone
[1] => optiontwo
[2] => optionthree
)
Which you then can access as you want it:
<?php
$example = array(
'optionone' => array('one', 'two', 'three'),
'optiontwo' => array('a','b','c'),
'optionthree' => array(1,2,3)
);
$keys = array_keys($example);
echo $keys[0] . "<br>";
echo $example[$keys[0]][0];
?>
output:
optionone
one
The outer array in your example is an associative array. There is not value at index 0. If you need to get to to the first key in the associative array without knowing the name of the key you would need to do something like:
$example = array(
'optionone' => array('one', 'two', 'three'),
'optiontwo' => array('a','b','c'),
'optionthree' => array(1,2,3)
);
//get array keys into array
$example_keys = array_keys($example);
// get value at first key in $example array
$first_inner_array = $example[$example_keys[0]];
// get first value from first inner array
$first_value = $first_inner_array[0];
// Or to get an arbitrary value:
$x = ... // whatever inner array you want to get into
$y = ... // whatever index within inner array you want to get to
$value = $example[$example+keys[$x]][$y];
I would say that if you find yourself doing this in code, you probably have your data structured poorly. Associative arrays are not meant to convey any sort of element ordering. For example, if you changed your example array to this:
$example = array(
'optiontwo' => array('a','b','c'),
'optionone' => array('one', 'two', 'three'),
'optionthree' => array(1,2,3)
);
You would get a different value retrieved from above code even though the relationship between outer array keys and inner array contents has not been changed.
not tested
foreach($example as $f_array){
foreach($f_array as $key => $val){ //iterate over each array inside first array
echo $key; //should print 'optionone'
echo $val[0]; //should print 'one'
break;
}
}
I have the following array, I'm trying to append the following ("","--") code
Array
(
[0] => Array
(
[Name] => Antarctica
)
)
Current JSON output
[{"Name":"Antarctica"}]
Desired output
{"":"--","Name":"Antarctica"}]
I have tried using the following:
$queue = array("Name", "Antarctica");
array_unshift($queue, "", "==");
But its not returning correct value.
Thank you
You can prepend by adding the original array to an array containing the values you wish to prepend
$queue = array("Name" => "Antarctica");
$prepend = array("" => "--");
$queue = $prepend + $queue;
You should be aware though that for values with the same key, the prepended value will overwrite the original value.
The translation of PHP Array to JSON generates a dictionary unless the array has only numeric keys, contiguous, starting from 0.
So in this case you can try with
$queue = array( 0 => array( "Name" => "Antarctica" ) );
$queue[0][""] = "--";
print json_encode($queue);
If you want to reverse the order of the elements (which is not really needed, since dictionaries are associative and unordered - any code relying on their being ordered in some specific way is potentially broken), you can use a sort function on $queue[0], or you can build a different array:
$newqueue = array(array("" => "--"));
$newqueue[0] += $queue[0];
which is equivalent to
$newqueue = array(array_merge(array("" => "--"), $queue[0]));
This last approach can be useful if you need to merge large arrays. The first approach is probably best if you need to only fine tune an array. But I haven't ran any performance tests.
Try this:
$queue = array(array("Name" => "Antarctica")); // Makes it multidimensional
array_unshift($queue, array("" => "--"));
Edit
Oops, just noticed OP wanted a Prepend, not an Append. His syntax was right, but we was missing the array("" => "--") in his unshift.
You can try this :
$queue = array("Name" => "Antarctica");
$result = array_merge(array("" => "=="), $queue);
var_dump(array_merge(array(""=>"--"), $arr));
I have an associative array which is generated dynamically with the values from database. When I print the whole array, it gives something like this when we put print_r($array).
Array ( [95a5c80811239526fb75cbf31740cc35] => Array ( [product_id] => 2324) )
When I echo like this,
echo $array['95a5c80811239526fb75cbf31740cc35']['product_id'];
it gives me product id.
But the problem is, the code '95a5c80811239526fb75cbf31740cc35' changes dynamically everytime. I want to echo the product id irrespective of this code.
I tried
$array[]['product_id'];
$array['']['product_id'];
But not working. Can anyone help me? Please ask me if you have any doubts.
You can use reset() in this case:
$array = array(
'95a5c80811239526fb75cbf31740cc35' => array( // dynamic
'product_id' => 2324
),
);
$value = reset($array); // set pointer to first element
echo $value['product_id']; // 2324
Assuming that the code is always the first element in the array:
$array[0]['product_id'];
If you collectively want all of the product ID's:
foreach($array as $product){
$productIds[] = $product['product_id'];
}
// $productIds is now what $array was, but without the codes, so the product_id's are the first elements.
You can use for each for this so that you can get the value of product Id
$array = Array ( [95a5c80811239526fb75cbf31740cc35] => Array ( [product_id] => 2324) )
foreach($array as $product){
echo $product['product_id'];
}
This would get your desired o/p
IF you are getting problem using Associative array then you can first convert it into numeric as follows
$arr=array( 'first' => array( 'product_id' => 2324) );
$arrr=array_values($arr);
echo $arrr[0]['product_id'];
Output:
2324
Hope this helps and to know about array_values go here
Depending on your situation, there are few possible solutions:
$array = array_shift(array_values(
Array(
'95a5c80811239526fb75cbf31740cc35' =>
Array(
'product_id' => 2324
)
)));
echo $array['product_id']; // 2324
Another solution, probably more efficient:
echo array_shift(array_slice($array, 0, 1)); // 2324
For PHP 5.4+ you could go with:
echo array_values($array)[0]; // 2324
$array[0]['product_id'];
Should do the trick.
I have an existing array to which I want to add a value.
I'm trying to achieve that using array_push() to no avail.
Below is my code:
$data = array(
"dog" => "cat"
);
array_push($data['cat'], 'wagon');
What I want to achieve is to add cat as a key to the $data array with wagon as value so as to access it as in the snippet below:
echo $data['cat']; // the expected output is: wagon
How can I achieve that?
So what about having:
$data['cat']='wagon';
If you need to add multiple key=>value, then try this.
$data = array_merge($data, array("cat"=>"wagon","foo"=>"baar"));
$data['cat'] = 'wagon';
That's all you need to add the key and value to the array.
You don't need to use array_push() function, you can assign new value with new key directly to the array like..
$array = array("color1"=>"red", "color2"=>"blue");
$array['color3']='green';
print_r($array);
Output:
Array(
[color1] => red
[color2] => blue
[color3] => green
)
For Example:
$data = array('firstKey' => 'firstValue', 'secondKey' => 'secondValue');
For changing key value:
$data['firstKey'] = 'changedValue';
//this will change value of firstKey because firstkey is available in array
output:
Array ( [firstKey] => changedValue [secondKey] => secondValue )
For adding new key value pair:
$data['newKey'] = 'newValue';
//this will add new key and value because newKey is not available in array
output:
Array ( [firstKey] => firstValue [secondKey] => secondValue [newKey]
=> newValue )
Array['key'] = value;
$data['cat'] = 'wagon';
This is what you need.
No need to use array_push() function for this.
Some time the problem is very simple and we think in complex way :) .
<?php
$data = ['name' => 'Bilal', 'education' => 'CS'];
$data['business'] = 'IT'; //append new value with key in array
print_r($data);
?>
Result
Array
(
[name] => Bilal
[education] => CS
[business] => IT
)
Just do that:
$data = [
"dog" => "cat"
];
array_push($data, ['cat' => 'wagon']);
*In php 7 and higher, array is creating using [], not ()
I have an array:
array( 4 => 'apple', 7 => 'orange', 13 => 'plum' )
I would like to get the first element of this array. Expected result: string apple
One requirement: it cannot be done with passing by reference, so array_shift is not a good solution.
How can I do this?
Original answer, but costly (O(n)):
array_shift(array_values($array));
In O(1):
array_pop(array_reverse($array));
Other use cases, etc...
If modifying (in the sense of resetting array pointers) of $array is not a problem, you might use:
reset($array);
This should be theoretically more efficient, if a array "copy" is needed:
array_shift(array_slice($array, 0, 1));
With PHP 5.4+ (but might cause an index error if empty):
array_values($array)[0];
As Mike pointed out (the easiest possible way):
$arr = array( 4 => 'apple', 7 => 'orange', 13 => 'plum' );
echo reset($arr); // Echoes "apple"
If you want to get the key: (execute it after reset)
echo key($arr); // Echoes "4"
From PHP's documentation:
mixed reset ( array | object &$array );
Description:
reset() rewinds array's internal pointer to the first element and returns the value of the first array element, or FALSE if the array is
empty.
$first_value = reset($array); // First element's value
$first_key = key($array); // First element's key
current($array)
returns the first element of an array, according to the PHP manual.
Every array has an internal pointer to its "current" element, which is initialized to the first element inserted into the array.
So it works until you have re-positioned the array pointer, and otherwise you'll have to use reset() which ll rewind array and ll return first element of array
According to the PHP manual reset.
reset() rewinds array's internal pointer to the first element and returns the value of the first array element.
Examples of current() and reset()
$array = array('step one', 'step two', 'step three', 'step four');
// by default, the pointer is on the first element
echo current($array) . "<br />\n"; // "step one"
//Forward the array pointer and then reset it
// skip two steps
next($array);
next($array);
echo current($array) . "<br />\n"; // "step three"
// reset pointer, start again on step one
echo reset($array) . "<br />\n"; // "step one"
$arr = $array = array( 9 => 'apple', 7 => 'orange', 13 => 'plum' );
echo reset($arr); // echoes 'apple'
If you don't want to lose the current pointer position, just create an alias for the array.
PHP 7.3 added two functions for getting the first and the last key of an array directly without modification of the original array and without creating any temporary objects:
array_key_first
array_key_last
Apart from being semantically meaningful, these functions don't even move the array pointer (as foreach would do).
Having the keys, one can get the values by the keys directly.
Examples (all of them require PHP 7.3+)
Getting the first/last key and value:
$my_array = ['IT', 'rules', 'the', 'world'];
$first_key = array_key_first($my_array);
$first_value = $my_array[$first_key];
$last_key = array_key_last($my_array);
$last_value = $my_array[$last_key];
Getting the first/last value as one-liners, assuming the array cannot be empty:
$first_value = $my_array[ array_key_first($my_array) ];
$last_value = $my_array[ array_key_last($my_array) ];
Getting the first/last value as one-liners, with defaults for empty arrays:
$first_value = empty($my_array) ? 'default' : $my_array[ array_key_first($my_array) ];
$last_value = empty($my_array) ? 'default' : $my_array[ array_key_last($my_array) ];
You can get the Nth element with a language construct, "list":
// First item
list($firstItem) = $yourArray;
// First item from an array that is returned from a function
list($firstItem) = functionThatReturnsArray();
// Second item
list( , $secondItem) = $yourArray;
With the array_keys function you can do the same for keys:
list($firstKey) = array_keys($yourArray);
list(, $secondKey) = array_keys($yourArray);
PHP 5.4+:
array_values($array)[0];
Some arrays don't work with functions like list, reset or current. Maybe they're "faux" arrays - partially implementing ArrayIterator, for example.
If you want to pull the first value regardless of the array, you can short-circuit an iterator:
foreach($array_with_unknown_keys as $value) break;
Your value will then be available in $value and the loop will break after the first iteration. This is more efficient than copying a potentially large array to a function like array_unshift(array_values($arr)).
You can grab the key this way too:
foreach($array_with_unknown_keys as $key=>$value) break;
If you're calling this from a function, simply return early:
function grab_first($arr) {
foreach($arr as $value) return $value;
}
Suppose:
$array = array( 4 => 'apple', 7 => 'orange', 13 => 'plum' );
Just use:
$array[key($array)]
to get first element or
key($array)
to get first key.
Or you can unlink the first if you want to remove it.
From Laravel's helpers:
function head($array)
{
return reset($array);
}
The array being passed by value to the function, the reset() affects the internal pointer of a copy of the array, and it doesn't touch the original
array (note it returns false if the array is empty).
Usage example:
$data = ['foo', 'bar', 'baz'];
current($data); // foo
next($data); // bar
head($data); // foo
next($data); // baz
Also, here is an alternative. It's very marginally faster, but more interesting. It lets easily change the default value if the array is empty:
function head($array, $default = null)
{
foreach ($array as $item) {
return $item;
}
return $default;
}
For the record, here is another answer of mine, for the array's last element.
Keep this simple! There are lots of correct answers here, but to minimize all the confusion, these two work and reduce a lot of overhead:
key($array) gets the first key of an array
current($array) gets the first value of an array
EDIT:
Regarding the comments below. The following example will output: string(13) "PHP code test"
$array = array
(
'1' => 'PHP code test',
'foo' => 'bar', 5 , 5 => 89009,
'case' => 'Random Stuff: '.rand(100,999),
'PHP Version' => phpversion(),
0 => 'ending text here'
);
var_dump(current($array));
Simply do:
array_shift(array_slice($array,0,1));
I would do echo current($array) .
$arr = array( 4 => 'apple', 7 => 'orange', 13 => 'plum' );
foreach($arr as $first) break;
echo $first;
Output:
apple
PHP 7.3 added two functions for getting the first and the last key of an array directly without modification of the original array and without creating any temporary objects:
array_key_first
array_key_last
"There are several ways to provide this functionality for versions prior to PHP 7.3.0. It is possible to use array_keys(), but that may be rather inefficient. It is also possible to use reset() and key(), but that may change the internal array pointer. An efficient solution, which does not change the internal array pointer, written as polyfill:"
<?php
if (!function_exists('array_key_first')) {
function array_key_first($arr) {
foreach($arr as $key => $unused) {
return $key;
}
return NULL;
}
}
if (!function_exists('array_key_last')) {
function array_key_last($arr) {
return array_key_first(array_reverse($arr, true));
}
}
?>
$myArray = array (4 => 'apple', 7 => 'orange', 13 => 'plum');
$arrayKeys = array_keys($myArray);
// The first element of your array is:
echo $myArray[$arrayKeys[0]];
$array=array( 4 => 'apple', 7 => 'orange', 13 => 'plum' );
$firstValue = each($array)[1];
This is much more efficient than array_values() because the each() function does not copy the entire array.
For more info see http://www.php.net/manual/en/function.each.php
A kludgy way is:
$foo = array( 4 => 'apple', 7 => 'orange', 13 => 'plum' );
function get_first ($foo) {
foreach ($foo as $k=>$v){
return $v;
}
}
print get_first($foo);
Most of these work! BUT for a quick single line (low resource) call:
$array = array( 4 => 'apple', 7 => 'orange', 13 => 'plum' );
echo $array[key($array)];
// key($array) -> will return the first key (which is 4 in this example)
Although this works, and decently well, please also see my additional answer:
https://stackoverflow.com/a/48410351/1804013
Use:
$first = array_slice($array, 0, 1);
$val= $first[0];
By default, array_slice does not preserve keys, so we can safely use zero as the index.
This is a little late to the game, but I was presented with a problem where my array contained array elements as children inside it, and thus I couldn't just get a string representation of the first array element. By using PHP's current() function, I managed this:
<?php
$original = array(4 => array('one', 'two'), 7 => array('three', 'four'));
reset($original); // to reset the internal array pointer...
$first_element = current($original); // get the current element...
?>
Thanks to all the current solutions helped me get to this answer, I hope this helps someone sometime!
<?php
$arr = array(3 => "Apple", 5 => "Ball", 11 => "Cat");
echo array_values($arr)[0]; // Outputs: Apple
?>
Other Example:
<?php
$arr = array(3 => "Apple", 5 => "Ball", 11 => "Cat");
echo current($arr); // Outputs: Apple
echo reset($arr); // Outputs: Apple
echo next($arr); // Outputs: Ball
echo current($arr); // Outputs: Ball
echo reset($arr); // Outputs: Apple
?>
I think using array_values would be your best bet here. You could return the value at index zero from the result of that function to get 'apple'.
Two solutions for you.
Solution 1 - Just use the key. You have not said that you can not use it. :)
<?php
// Get the first element of this array.
$array = array( 4 => 'apple', 7 => 'orange', 13 => 'plum' );
// Gets the first element by key
$result = $array[4];
// Expected result: string apple
assert('$result === "apple" /* Expected result: string apple. */');
?>
Solution 2 - array_flip() + key()
<?php
// Get first element of this array. Expected result: string apple
$array = array( 4 => 'apple', 7 => 'orange', 13 => 'plum' );
// Turn values to keys
$array = array_flip($array);
// You might thrown a reset in just to make sure
// that the array pointer is at the first element.
// Also, reset returns the first element.
// reset($myArray);
// Return the first key
$firstKey = key($array);
assert('$firstKey === "apple" /* Expected result: string apple. */');
?>
Solution 3 - array_keys()
echo $array[array_keys($array)[0]];
No one has suggested using the ArrayIterator class:
$array = array( 4 => 'apple', 7 => 'orange', 13 => 'plum' );
$first_element = (new ArrayIterator($array))->current();
echo $first_element; //'apple'
gets around the by reference stipulation of the OP.
I imagine the author just was looking for a way to get the first element of an array after getting it from some function (mysql_fetch_row, for example) without generating a STRICT "Only variables should be passed by reference".
If it so, almost all the ways described here will get this message... and some of them uses a lot of additional memory duplicating an array (or some part of it). An easy way to avoid it is just assigning the value inline before calling any of those functions:
$first_item_of_array = current($tmp_arr = mysql_fetch_row(...));
// or
$first_item_of_array = reset($tmp_arr = func_get_my_huge_array());
This way you don't get the STRICT message on screen, nor in logs, and you don't create any additional arrays. It works with both indexed AND associative arrays.
Use array_keys() to access the keys of your associative array as a numerical indexed array, which is then again can be used as key for the array.
When the solution is arr[0]:
(Note, that since the array with the keys is 0-based index, the 1st
element is index 0)
You can use a variable and then subtract one, to get your logic, that 1 => 'apple'.
$i = 1;
$arr = array( 4 => 'apple', 7 => 'orange', 13 => 'plum' );
echo $arr[array_keys($arr)[$i-1]];
Output:
apple
Well, for simplicity- just use:
$arr = array( 4 => 'apple', 7 => 'orange', 13 => 'plum' );
echo $arr[array_keys($arr)[0]];
Output:
apple
By the first method not just the first element, but can treat an associative array like an indexed array.
I don't like fiddling with the array's internal pointer, but it's also inefficient to build a second array with array_keys() or array_values(), so I usually define this:
function array_first(array $f) {
foreach ($f as $v) {
return $v;
}
throw new Exception('array was empty');
}
This is not so simple response in the real world. Suppose that we have these examples of possible responses that you can find in some libraries.
$array1 = array();
$array2 = array(1,2,3,4);
$array3 = array('hello'=>'world', 'foo'=>'bar');
$array4 = null;
var_dump('reset1', reset($array1));
var_dump('reset2', reset($array2));
var_dump('reset3', reset($array3));
var_dump('reset4', reset($array4)); // Warning
var_dump('array_shift1', array_shift($array1));
var_dump('array_shift2', array_shift($array2));
var_dump('array_shift3', array_shift($array3));
var_dump('array_shift4', array_shift($array4)); // Warning
var_dump('each1', each($array1));
var_dump('each2', each($array2));
var_dump('each3', each($array3));
var_dump('each4', each($array4)); // Warning
var_dump('array_values1', array_values($array1)[0]); // Notice
var_dump('array_values2', array_values($array2)[0]);
var_dump('array_values3', array_values($array3)[0]);
var_dump('array_values4', array_values($array4)[0]); // Warning
var_dump('array_slice1', array_slice($array1, 0, 1));
var_dump('array_slice2', array_slice($array2, 0, 1));
var_dump('array_slice3', array_slice($array3, 0, 1));
var_dump('array_slice4', array_slice($array4, 0, 1)); // Warning
list($elm) = $array1; // Notice
var_dump($elm);
list($elm) = $array2;
var_dump($elm);
list($elm) = $array3; // Notice
var_dump($elm);
list($elm) = $array4;
var_dump($elm);
Like you can see, we have several 'one line' solutions that work well in some cases, but not in all.
In my opinion, you have should that handler only with arrays.
Now talking about performance, assuming that we have always array, like this:
$elm = empty($array) ? null : ...($array);
...you would use without errors:
$array[count($array)-1];
array_shift
reset
array_values
array_slice
array_shift is faster than reset, that is more fast than [count()-1], and these three are faster than array_values and array_slice.