Dynamically access an object property array element in PHP - php

I have an object, that I would like to interact with dynamically. I would like to rename the game1_team1 in:
$default_value = $individual_match->field_match_game1_team1[0]['value'];
to be game1_team2, game2_team1, game2_team2, game3_team1, etc. Based on the loop they are in.
I have tried:
$dynamic = 'field_match_game'.$i.'_team'.$j;
$default_value = $individual_match->$dynamic[0]['value'];
but it returns
Fatal error: Cannot use string offset
as an array
Update: Based on Saul's answer, I modified the code to:
$default_value = $individual_match->{'field_match_game'.$i.'_team'.$j}[0]['value'];
which got rid of the Fatal error, but doesn't return a value.

$individual_match->field_match_game1team1[0]['value'] = 'hello1';
$i = 1;
$j = 1;
$default_value = $individual_match->{'field_match_game'.$i.'team'.$j}[0]['value'];

'Renaming' is not possible unless you create a new property, and delete the old one.
Access dynamic names like this:
$dynamic = "field_match_$i_team$j";
$default_value = $individual_match->$dynamic[0]['value'];
Note the $ between -> and dynamic.
Delete and create example:
$oldProperty = "field_match_1_team1";
$newProperty = "field_match_$i_team$j";
$hold = $individual_match->$oldProperty;
unset($individual_match->$oldProperty);
$individual_match->$newProperty = $hold;

Look at this : http://php.net/manual/en/function.get-class-vars.php
You can list all object's properties in array and select only needed.

Related

Fatal error: Can't use function return value in write context error in PHP

I need to get values of html element name 'item_name1','item_name2','item_name3'...so on using loop. But it is showing this fatal error. Please help to resolve...
Code is:
$item_name = array();
$item_qty = array();
$item_value = array();
for($i=1;$i<=php_count;$i++){
$item_name($i) = $_POST['item_name+$i'];
$item_qty($i) = $_POST['item_qty+$i'];
$item_value($i) = $_POST['item_value+$i'];
echo($item_name($i));
}
You need square brackets [ ] instead of parentheses ( ) when accessing your arrays. The former are used for array indexing while the latter are used for function calls.
Since you are essentially calling your array like a function and you have the result of that call on the left-hand side of an assignment, you are getting the error that you can't write to a function return value.
And by the way: Currently you are literally accessing the indexes item_name+$i and such of $_POST because you have the +$i part inside of the string. Use $_POST['item_name' + $i] instead.
as requested
use square brackets for array elements
use double quotes to allow variable processing within string context
use variable for php count
$item_name = array();
$item_qty = array();
$item_value = array();
for($i=1;$i<=$items_count;$i++){
$item_name[$i]= $_POST[“item_name+$i”];
$item_qty[$i] = $_POST[“item_qty+$i”];
$item_value[$i] = $_POST[“item_value+$i”];
echo($item_name[$i]);
}
———
alternative solution
simplify by changing your form input names to allow arrays of data
Input names such as item[0][name] would allow you to simply loop through an item array!
foreach($_POST['item'] as $item) {
$item_name = $item['name'];
...
Your code have to like this
$item_name[$i] = $_POST['item_name'.$i];
$item_qty[$i] = $_POST['item_qty'.$i];
$item_value[$i] = $_POST['item_value'.$i];
echo($item_name[$i]);

PHP how to add slashes into array

i have a problem i want to add slashes at the starting and the end of each string of my array.
This is an example of my actual array :
$patte = array();
$patte[0] = "httpd";
$patte[1] = "vsftpd";
$patte[2] = 'gohphp';
$patte[3] = 'abcdef';
i use this array for taking information into a DataBase so i can't place slashes now, or this is going to not working.
(mysql_query ... while mysql_fetch_array ...)
I need to rename these entry.
For this i use a second array, and with the command : "preg_replace" i can translate every strings like i want.
But preg_replace want me to add slashes in $patte
I want to obtain an array like this
$pattes = array();
$pattes[0] = "/httpd/";
$pattes[1] = "/vsftpd/";
$pattes[2] = '/gohphp/';
$pattes[3] = '/abcdef/';
Can you help me please.
I'm gonna have like 1000 line into this array.
Using array_map() you can apply callback to every element of your array :
function addSlashes($str)
{
return "/".$str."/";
}
$newArray = array_map("addSlashes", $patte);//array with the new values
Use array_map:
$pattes = array_map(function($str) {
return '/'.$str.'/';
}, $pattes);

Initializing array and getting reference in one line

I want to initialize array(in my case it's multidimensional) and I want to retrieve reference to a separate variable so i could access it via that variable.
For example to achieve this im writing two lines
$multidimensional[$some_key] = array();
$item = &$multidimensional[$some_key];
This thing works just fine, but if I wanted to do this in one like I had tried:
$item = &$multidimensional[$some_key] = array(); // syntax error
Question is there a way to do this in single line?
How about:
$item = &($multidimensional[$some_key] = array());
?

Add to array if set

Is there a better/shorter way to do this?
Each variable is a MySQL table value that is called. I have a main table and an override table, so call the first table, extract the resulting array, then call the override table and extract those results to override the first extract.
if (isset($Price1)){
$AllPrices[] = $Price1;}
if (isset($Price2)){
$AllPrices[] = $Price2;}
if (isset($Price3)){
$AllPrices[] = $Price3;}
if (isset($Price4)){
$AllPrices[] = $Price4;}
if (isset($SPrice1)){
$AllPrices[] = $SPrice1;}
if (isset($SPrice2)){
$AllPrices[] = $SPrice2;}
if (isset($SPrice3)){
$AllPrices[] = $SPrice3;}
I've done things like this in the past, but I wouldn't recommend it:
$variables = array("Price1", "Price2", "Price3", "Price4", "SPrice1", "SPrice2", "SPrice3");
$AllPrices = array();
foreach ($variables as $variable)
{
if (isset($$variable))
$AllPrices[] = $$variable;
}
See here for more information on how the $$ syntax works in PHP.
But I do agree with the comments to your post... You really should take another look at how you're getting this data. This solution is not ideal in the least.
You can also do like this:
for($i = 1; $i < 4; $i++){
$current = ${'AllPrices'.$i};
isset($current) && array_push($AllPrices, $current);
}
As also posted in above answer, using array of variable names is more efficient.
This structure is not recommended.
Instead of using $price1, $price2, ... use an array - $price[1], $price[2], ... (Do the same for $SPrice).
Then you could use a simple array_merge:
$AllPrices = array_merge($price, $SPrice);

Creating an array in PHP

If I wanted to create an array in PHP with the following format, what would be the best way to approach it? Basically I want to declare the array beforehand, and then be able to add the values to person_id, name and age.
'person_id' => array('name'=>'jonah', 'age'=> 35)
To the first answer #Joe, first of all, your class doesn't support encapsulation since your attributes are public. Also, for someone who doesn't know how to create an array, this concept may be a bit complicated.
For the answer, changing a bit the class provided by #Joe, PHP provide a simple way of using arrays:
If you need many rows for this array, each row has a number, if not, remove the [0] for only one entry.
$persons = array();
$persons[0]['person_id'] = 1;
$persons[0]['name'] = 'John';
$persons[0]['age'] = '27';
Depending on how you want to use it, you could make a simple object:
class Person
{
public $person_id;
public $name;
public $age;
}
$person = new Person; // make the object beforehand
$person->person_id = 123; // their id
$person->name = 'Joe'; // my name
$person->age = 21; // yeah, right
This is virtually identical to an array (in terms of how it's used) except for:
Instead of new array() you use new Person (no brackets)
Instead of accessing items with ['item'] you use ->item
You can start with an empty array:
$arr = Array();
Then add stuff to that array:
$arr['person_id'] = Array();
$arr['person_id']['name'] = "jonah";
$arr['person_id']['age'] = 35;

Categories