Get key from an array in smarty - php

If I have an array that looks like this:
$my_array = array(2) { ["mykey"]=> int(2) ["mysecondkey"]=> int(3) }
How can I get to the key value of the first element?.
So far I know I can do $my_array[0], but how do I get to the first key? I want to avoid doing foreach.
Thanks!

This is associative array (string keys). Use name of key directly:
$my_array["mykey"];
Read more here
To extract keys use array_keys:
$my_array = array(2) { ["mykey"]=> int(2) ["mysecondkey"]=> int(3) }
$keys = array_keys($my_array); //0 => "mykey", 1 => "mysecondkey"

You can use array_keys() to get a list of your array's keys:
$keys = array_keys($my_array);
echo $keys[0]; // outputs "mykey"
If you want to do this in Smarty, you can use the following code to output the array's first key:
{foreach from=$my_array key=my_key item=i name=my_array}
{if $smarty.foreach.my_array.first}{$my_key}{/if}
{/foreach}

foreach($my_array as $key=>$_val){
echo $key;
break;
}

array_keys() will get all the keys in an array, while this will get the first key without iterating all the others and ignoring the rest of the array.
It is a fake loop as the break will exit at the first iteration, so you are not actually doing a real foreach for all the values.
foreach($my_array as $firstKey=>$unused) {
break;
}
echo($firstKey);
If you need a function, you may use this:
function first_key($arr) {
foreach($my_array as $firstKey=>$unused) {
return $firstKey;
}
}
Again the function returns at the first iteration, so you are not doing a "real" foreach on all the elements.

Related

How to get element from array?

How to get single element from this?
array(1) { [0]=> object(stdClass)#3 (2) { ["id"]=> int(29595) ["image_id"]=> string(20) "eohsidatfx8wyw5ltzt6" } }
I need to separate "image_id". How to do it? I tried
echo $result["image_id"]
but it doesn't work:
Notice: Undefined index: image_id in C:\xampp\htdocs\IGDB\moje\index.php on line 53
It seems your array only directly contains object(stdClass)#3. This object is itself an array containing id and image_id. You can access image_id by doing
echo $result[0]["image_id"];
Ok, got it.
$result3=array_column($result2, 'image_id');
echo $result3[0];
$myArray = array(
'#3' => array (
"id"=> 29595,
"image_id"=> "eohsidatfx8wyw5ltzt6"
)
);
what you are looking for is in the second level of your array.
Use a foreach loop to iterate of the arrays key/value pairs.
foreach($myArray as $value){
foreach($value as $key => $id){
if($key === 'image_id'){
$output = $id;// output now holds the vlaue of the key set with 'image_id'
}
}
}
If you know the value of the key, you can also access this by using the keys like so: $arrayname['firstlevelkey']['secondlevelkey'];
Notice: Undefined index: image_id in C:\xampp\htdocs\IGDB\moje\index.php on line 53
--> This is because you are defining an array with a key that does not exist in the array
echo $result["image_id"] --> here you are telling php that "image_id" is on the first level of the array, however, it looks to be nested in the second layer of the array you are trying to parse. $result['#3']['image_id'].
If you are not sure, write a conditional that looks in the first array using is_array(), if the first is a key value holding a child array. Then run the foreach loop again to look for the key/pair value.
foreach($arr as $values){
// do something if value is string
if(is_array($values){
foreach($values as $key => $value){
// check your second level $key/$value
}
}
}

How to get value by value of an array

I got a problem, I got a array from a sql query and I want to associate each value of this array to an index value.
array(16) { ["noCommande"]=> string(5) "49083" ["dateCommande"]=> string(19) "2007-02-21 18:24:04" ...
So here I just want to get back each value one per one. The array[i] doesn't work so I am a bit in trouble.
Thanks you for your support.
It's associative array, values are in
$array['noCommande'];
$array['dateCommande'];
etc.
If you want to ake a loop over array and write all values,
foreach ($array as $key => $value) {
echo $key . ': ' . $value; // echoes 'noCommande: 49083', etc.
}
You can iterate like below:-
foreach($your_array as $key=>$value){
echo $key.'-'.$value;
echo "<br/>";//for new line to show in a good manner
}
It will output like :- noCommande - 49083 and etc.

PHP Find Array Index Name

Let's say I have an array that looks like this when I perform a var_dump:
array(1) { [300000001]=> string(15) "Find Compatible" }
Instead of printing the value "Find Compatible", how can I use the index name 300000001 as a variable?
first key:
$first_key = key($array);
search based on value:
$key=array_search('Find Compatible',$array);
If you want to get all the keys of a given $array, you can iterate using foreach:
foreach ($array as $key => $value) {
echo $key;
}

Can items in PHP associative arrays not be accessed numerically (i.e. by index)?

I'm trying to understand why, on my page with a query string,
the code:
echo "Item count = " . count($_GET);
echo "First item = " . $_GET[0];
Results in:
Item count = 3
First item =
Are PHP associative arrays distinct from numeric arrays, so that their items cannot be accessed by index? Thanks-
They can not. When you subscript a value by its key/index, it must match exactly.
If you really wanted to use numeric keys, you could use array_values() on $_GET, but you will lose all the information about the keys. You could also use array_keys() to get the keys with numerical indexes.
Alternatively, as Phil mentions, you can reset() the internal pointer to get the first. You can also get the last with end(). You can also pop or shift with array_pop() and array_shift(), both which will return the value once the array is modified.
Yes, the key of an array element is either an integer (must not be starting with 0) or an associative key, not both.
You can access the items either with a loop like this:
foreach ($_GET as $key => $value) {
}
Or get the values as an numerical array starting with key 0 with the array_values() function or get the first value with reset().
You can do it this way:
$keys = array_keys($_GET);
echo "First item = " . $_GET[$keys[0]];
Nope, it is not possible.
Try this:
file.php?foo=bar
file.php contents:
<?php
print_r($_GET);
?>
You get
Array
(
[foo] => bar
)
If you want to access the element at 0, try file.php?0=foobar.
You can also use a foreach or for loop and simply break after the first element (or whatever element you happen to want to reach):
foreach($_GET as $value){
echo($value);
break;
}
Nope -- they are mapped by key value pairs. You can iterate the they KV pair into an indexed array though:
foreach($_GET as $key => $value) {
$getArray[] = $value;
}
You can now access the values by index within $getArray.
As another weird workaround, you can access the very first element using:
print $_GET[key($_GET)];
This utilizes the internal array pointer, like reset/end/current(), could be useful in an each() loop.

Can I use array_push on a SESSION array in php?

I have an array that I want on multiple pages, so I made it a SESSION array. I want to add a series of names and then on another page, I want to be able to use a foreach loop to echo out all the names in that array.
This is the session:
$_SESSION['names']
I want to add a series of names to that array using array_push like this:
array_push($_SESSION['names'],$name);
I am getting this error:
array_push() [function.array-push]:
First argument should be an array
Can I use array_push to put multiple values into that array? Or perhaps there is a better, more efficient way of doing what I am trying to achieve?
Yes, you can. But First argument should be an array.
So, you must do it this way
$_SESSION['names'] = array();
array_push($_SESSION['names'],$name);
Personally I never use array_push as I see no sense in this function. And I just use
$_SESSION['names'][] = $name;
Try with
if (!isset($_SESSION['names'])) {
$_SESSION['names'] = array();
}
array_push($_SESSION['names'],$name);
$_SESSION['total_elements']=array();
array_push($_SESSION['total_elements'], $_POST["username"]);
Yes! you can use array_push push to a session array and there are ways you can access them as per your requirement.
Basics:
array_push takes first two parameters array_push($your_array, 'VALUE_TO_INSERT');.
See: php manual for reference.
Example:
So first of all your session variable should be an array like:
$arr = array(
's_var1' => 'var1_value',
's_var2' => 'var2_value'); // dummy array
$_SESSION['step1'] = $arr; // session var "step1" now stores array value
Now you can use a foreach loop on $_SESSION['step1']
foreach($_SESSION['step1'] as $key=>$value) {
// code here
}
The benefit of this code is you can access any array value using the key name for eg:
echo $_SESSION[step1]['s_var1'] // output: var1_value
NOTE: You can also use indexed array for looping like
$arr = array('var1_value', 'var1_value', ....);
BONUS:
Suppose you are redirected to a different page
You can also insert a session variable in the same array you created. See;
// dummy variables names and values
$_SESSION['step2'] = array(
's_var3' => 'page2_var1_value',
's_var4' => 'page2_var2_value');
$_SESSION['step1step2'] = array_merge($_SESSION['step1'], $_SESSION['step2']);
// print the newly created array
echo "<pre>"; // for formatting printed array
var_dump($_SESSION['step1step2']);
echo "<pre>";
OUTPUT:
// values are as per my inputs [use for reference only]
array(4) {
["s_var1"]=>
string(7) "Testing"
["s_var2"]=>
int(4) "2124"
["s_var3"]=>
int(4) "2421"
["s_var4"]=>
string(4) "test"
}
*you can use foreach loop here as above OR get a single session var from the array of session variables.
eg:
echo $_SESSION[step1step2]['s_var1'];
OUTPUT:
Testing
Hope this helps!
Try this, it's going to work :
session_start();
if(!isset($_POST["submit"]))
{
$_SESSION["abc"] = array("C", "C++", "JAVA", "C#", "PHP");
}
if(isset($_POST["submit"]))
{
$aa = $_POST['text1'];
array_push($_SESSION["abc"], $aa);
foreach($_SESSION["abc"] as $key => $val)
{
echo $val;
}
}
<?php
session_start();
$_SESSION['data']= array();
$details1=array('pappu','10');
$details2=array('tippu','12');
array_push($_SESSION['data'],$details1);
array_push($_SESSION['data'],$details2);
foreach ($_SESSION['data'] as $eacharray)
{
while (list(, $value) = each ($eacharray))
{
echo "Value: $value<br>\n";
}
}
?>
output
Value: pappu Value: 10 Value: tippu Value: 12

Categories