key and value array access in php - php

I am calling a function like:
get(array('id_person' => $person, 'ot' => $ot ));
In function How can I access the key and value as they are variable?
function get($where=array()) {
echo where[0];
echo where[1];
}
How to extract 'id_person' => $person, 'ot' => $ot without using foreach as I know how many key-values pairs I have inside function?

You can access them via $where['id_person'] / $where['ot'] if you know that they will always have these keys.
If you want to access the first and second element, you can do it like this
reset($where)
$first = current($where);
$second = next($where);

Couple ways. If you know what keys to expect, you can directly address $where['id_person']; Or you can extract them as local variables:
function get($where=array()) {
extract($where);
echo $id_person;
}
If you don't know what to expect, just loop through them:
foreach($where AS $key => $value) {
echo "I found $key which is $value!";
}

Just do $where['id_person'] and $where['ot'] like you do in JavaScript.

If you do not care about keys and want to use array as ordered array you can shift it.
function get($where=array()) {
$value1 = array_shift($where);
$value2 = array_shift($where);
}

Related

PHP dynamic array name with loop

I need to get values of array through a loop with dynamic vars.
I can't understand why the "echo" doesn’t display any result for "$TAB['b']".
Do you know why ?
The test with error message : https://3v4l.org/Fp3GT
$TAB_a = "aaaaa";
$TAB['b'] = "bbbbb";
$TAB['b']['c'] = "ccccc";
$TAB_paths = ["_a", "['b']", "['b']['c']"];
foreach ($TAB_paths as $key => $value) {
echo "\n\n\${'TAB'.$value} : "; print_r(${'TAB'.$value});
}
You are treating the array access characters as if they are part of the variable name. They are not.
So if you have an array $TAB = array('b' => 'something');, the variable name is $TAB. When you do ${'TAB'.$value}, you're looking for a variable that's actually named $TAB['b'], which you don't have.
Since you say that you just want to be able to access array indexes dynamically based on the values in another array, you just put the indexes alone (without the array access characters) in the other array.
$TAB['b'] = 'bbbbbb';
$TAB['c'] = 'cccccc';
$TAB_paths = array('b', 'c');
foreach ($TAB_paths as $key => $value) {
echo "\n\n".'$TAB['."'$value'".'] : ' . $TAB[$value];
}
Output:
$TAB['b'] : bbbbbb
$TAB['c'] : cccccc
DEMO
It's unclear what you're trying to do, although you need to include $TAB_all in $TAB_paths:
$TAB_paths = [$TAB_all['a'], $TAB_all['aside']['nav']];
Result:
${TAB_all.aaaaa} : ${TAB_all.bbbbb} :
Not certain what you're needing. My guess you need to merge two arrays into one. Easiest solution is to use the array_merge function.
$TAB_paths = array_merge($TAB_a1, $TAB_a2);
You can define the variable first
foreach ($TAB_all as $key => $value) {
${"TAB_all" . $key} = $value;
}
Now Explore the result:
foreach ($TAB_all as $key => $value) {
print_r(${"TAB_all" . $key});
}

php: how to get name from object

this might be very simple, and well, yes ... I may not fully understand how objects work, which seems to be the real problem here. So thanks for helping! ^^
I've got an Object that kinda looks like this.
$myobject = Array( [some_random_name] => "Value to that random name" )
Since I'm not sure how those two bits of information are called (sry for that) I will refer to them as "name" and "value". My question is: how do I extract these informations? I need both, the "name" and the "value", so I can store them in two variables ($namevar, $nameval), which should then output something like this:
echo($namevar) = "some_random_name"
echo($nameval) = "Value to that random name"
Thanks.
well, you are using an Array, not an object. in order to get the array keys or values, you could use the following functions: array_values & array_keys.
i could add code snippets etc, but its really straight forward in php's docs:
http://php.net/manual/en/function.array-values.php
http://php.net/manual/en/function.array-keys.php
you could also possibly iterate the array or object (works the same for both), using something like the following code:
foreach($object as $key => $value) { ... }
you can use :
$myobject = [ 'key' => 'value' ];
$key = key($myobject);
$value = $myobject[$key];
echo $key; // key
echo $value; // value
it will return the key value for the current array element
see documentation
or you can use a foreach loop like this:
foreach($myobject as $key => $value) {
$namevar = $key;
$nameval = $value;
}
Basically you are asking how do we get the value of array objects? how do we use them?
These are array objects.
echo $yourObjectname->yourpropertyname;
in your case
echo $myobject->some_random_name;
Example -
$arr = Array (
[0] => stdClass Object (
[name] => 'abc'
);
echo $arr[0]->name;
Object is an instance of class or we can say an medium to use classes properties variable and methods.

php - Find array for which a key have a given value

I have an array of dictionnaries like:
$arr = array(
array(
'id' => '1',
'name' => 'machin',
),
array(
'id' => '2',
'name' => 'chouette',
),
);
How can I find the name of the array containing the id 2 (chouette) ?
Am I forced to reindex the array ?
Thank you all, aparently I'm forced to loop through the array (what I wanted to avoid), I thought that it were some lookup fonctions like Python. So I think I'll reindex with id.
Just find the index of array that contains the id you want to find.
SO has enough questions and answers on this topic available.
Assuming you have a big array with lots of data in your real application, it might be too slow (for your taste). In this case, you indeed need to modify the structure of your arrays, so you can look it up faster, e.g. by using the id as an index for the name (if you are only interested in the name).
As a for loop would be the best way to do this, I would suggest changing you array so that the id is the arrays index. For example:
$arr = array(
1 => 'machin',
2 => 'chouette',
);
This way you could just get the name for calling $arr[2]. No looping and keeping your program running in linear time.
$name;
foreach ($arr as $value){
if ( $value['id'] == 2 ){
$name = $value['name'];
break;
}
}
I would say that it might be very helpful to reindex the information. If the ID is unique try something like this:
$newarr = array();
for($i = 0;$i < count($arr);$i++){ $newarr[$arr[$i]['id']] = $arr[$i]['name']; }
The result would be:
$newarr = array('1'=>'machin','2'=>'chouette');
Then you can go trough the array with "foreach" like this:
foreach($newarr as $key => $value){
if($value == "machin"){
return $key;
}
}
But of course the same would work with your old array:
foreach($arr as $item){
if($item['name'] == "machin"){
return $item['id'];
}
}
It depends on what you are planning to do with the array ;-)
array_key_exist() is the function to check for keys. foreach will help you get down in the multidimensional array. This function will help you get the name element of an array and let you specify a different id value.
function findKey($bigArray, $idxVal) {
foreach($bigArray as $array) {
if(array_key_exists('id', $array) && $array['id'] == $idxVal) {
return $array['name'];
}
}
return false;
}
//Supply your array for $arr
print(findKey($arr, '2')); //"chouette"
It's a bit crude, but this would get you the name...
$name = false;
foreach($arr as $v) {
if($v['id'] == '2') {
$name = $v['name'];
break;
}
}
echo $name;
So no, you are not forced to reindex the array, but it would make things easier.

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

to print values of an array after extracting the array in php

Please help in code that i am unable to print values of associative array after extracting itself
class display{
protected $variables = array();
function set($name,$value) {
$this->variables[$name] = $value;
}
function render(){
extract($this->variables);
// ?? to print values of $variable array
}
foreach($this->variables as $key => $value) {
echo "{$key}: {$value}\n";
}
And how do you try to print the values? The array itself (it's $varables, not $variable, btw) should not be affected.
Update: For what I can tell by your reply to the other answer, you do not really need to extract array. extract jusst puts the variables into local namespace where they will be harder to enumerate. What you need is to use array as is.
foreach($this->variables as $k => $v) echo "$k: $v\n";
or whatever you want to do with them.
if you are using classes, u will need to have something like
var $variables = array(); or
public $variables = array();
and if you are using structured , you will need to do
global $variables;
inside the function .. but as u are using $this-> it indicates ur using a class. You will have to put in some more code in here to make the situation clear.

Categories