PHP Find Array Index Name - php

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

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.

Getting the name of an array dynamically

I have an array which looks like this:
$example = [
['rendered'][0]['rendereditem1']
['rendered'][4]['rendereditem2 and more']
['rendered'][2]['rendereditem3']
]
Now I want to iterate with foreach to get the contents of 0,4,2!
Normally I would write:
foreach($example as $value){
print $value['rendered'][int which is the same everywhere];
}
But that is obviously not working because the array name is always different...how could I iterate in this case?
Simply add a second loop to iterate over the members :
foreach($example as $value) {
foreach($value['rendered'] as $key=>$item) {
// Do what you want here, $key is 0,4,2 in your example
}
}

Get key from an array in smarty

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.

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