PHP possible to initial array with value from same array? - php

I want to save current path information in an Array and one field is a part of another. Can I access a field of the same array during initialization?
$this->path = array
(
'rel_image' => '/images',
'document_path' => '/a/file/path',
'path' => $this->path['document_path'].$this->path['rel_images']
);
or do I have to initial them one by one?

The array still is undefined while you're defining it. However you can define other (temporary) variables to do so on the fly:
$this->path = array
(
'rel_image' => $r = '/images',
'document_path' => $p = '/a/file/path',
'path' => $p.$r
);
However that normally should not be needed, as you're duplicating data within the array. Just saying, you can do whatever you want :)

You have to initialize them one by one.
It is best to think of array as a constructor. The array itself doesn't completely exist until after the function call is complete, and you can't access something which doesn't completely exist in most circumstances.

yes, you have to initialize one by one, beacuse $this->path is being filled after array() function is done.

As far as I know, the assignment you're trying to do isn't a functional one.
Code:
<?php $array = array('foo' => 'bar', 'bar' => $array['foo']); ?>
<pre><?php print_r($array); ?></pre>
...renders the following:
Array
(
[foo] => bar
[bar] =>
)
As the array is created at one time, not once per element, it will not be able to reference the values in the same statement as the assignment.

Related

Print result is different in the array function

I have a problem with the array PHP function, below is my first sample code:
$country = array(
"Holland" => "David",
"England" => "Holly"
);
print_r ($country);
This is the result Array ( [Holland] => David [England] => Holly )
I want to ask, is possible to make the array data become variables? For second example like below the sample code, I want to store the data in the variable $data the put inside the array.:
$data = '"Holland" => "David","England" => "Holly"';
$country = array($data);
print_r ($country);
But this result is shown me like this: Array ( [0] => "Holland" => "David","England" => "Holly" )
May I know these two conditions why the results are not the same? Actually, I want the two conditions can get the same results, which is Array ( [Holland] => David [England] => Holly ).
Hope someone can guide me on how to solve this problem. Thanks.
You can use the following Code.
<?php
$country = array(
"Holland" => "David",
"England" => "Holly"
);
foreach ($country as $index => $value)
{
$$index = $value;
}
?>
Now, Holland & England are two variables. You can use them using $Holland etc.
A syntax such as $$variable is called Variable Variable. Actually The inner $ resolves the a variable to a string, and the outer one resolves a variable by that string.
So there is this thing called
Destructuring
You can do it something like ["Holland" => $eolland, "England" => $england] = $country;
And now you have your array elements inside the variables.
Go read the article above if you want more information about this because it gets really useful (especially in unit tests usind data provders from my experience).
If you want to extract elements from an associative array such that the keys become variable names and values become the value of that variable you can use extract
extract($country);
To check what changed you can do
print_r(get_defined_vars());
Explanation on why the below does not work
$data = '"Holland" => "David","England" => "Holly"';
When you enclose the above in single quotes ' php would recognise it as a string. And php will parse a string as a string and not as an array.
Do note it is not enough to create a string with the same syntax as the code and expect php to parse it as code. The codes will work if you do this
$data = ["Holland" => "David","England" => "Holly"];
However, now $data itself is an array.
A simple copy of an array can be made by using
$data = $country;

PHP rename key in Associative array

I've been searching through the articles on SO for this question and tried many of the solutions in my own code but it's not seeming to work.
I have the following array
$array[] = array("Order_no"=>$order_id,
"Customer"=>$customer_id,
"Product"=>$code_po,
"Product_description"=>$code_description,
"Position"=>$pos,
"Qty"=>$item_qty
);
I am looking to replace the "Order_no" key with a variable from a database query, lets assume in this case the variable is "new_name"
$new = "new_name";
$array[$new]=$array["Order_no"];
unset($array["Order_no"]);
print_r($array);
in the print_r statement I am getting the new_name coming through as the correct order number, but I am still seeing "Order_no" there also, which I shouldn't be seeing anymore.
Thanks.
This is your array:
Array
(
[0] => Array
(
[Customer] => 2
[Product] => 99
[Order_no] => 12345
)
)
One way to do it:
<?php
$arr[] = [
"Order_no" => 12345,
"Customer" => 00002,
"Product"=> 99
];
$i_arr = $arr[0];
$i_arr["new_name"] = $i_arr["Order_no"];
unset($i_arr["Order_no"]);
$arr[0] = $i_arr;
print_r($arr);
Another way:
<?php
$arr[] = [
"Order_no" => 12345,
"Customer" => 00002,
"Product"=> 99
];
$arr[0]["new_name"] = $arr[0]["Order_no"];
unset($arr[0]["Order_no"]);
print_r($arr);
To flatten your array out at any time:
<?php
$arr = $arr[0];
print_r($arr);
You are using extra level of array (by doing $array[] = ...).
You should do it with [0] as first index as:
$array[0][$new]=$array[0]["Order_no"];
unset($array[0]["Order_no"]);
Live example: 3v4l
Another option is get ride of this extra level and init the array as:
$array = array("Order_no"=>$order_id, ...
As $array is also an array, you have to use index:
$array[0][$new]=$array[0]["Order_no"];
unset($array[0]["Order_no"]);
The other answers will work for the first time you add to the array, but they will always work on the first item in the array. Once you add another it will not work, so get the current key:
$array[key($array)][$new] = $array[key($array)]["Order_no"];
unset($array[key($array)]["Order_no"]);
If you want the first one, then call reset($array); first.
Change your variable to
$array=array("Order_no"=>$order_id,"Customer"=>$customer_id,"Product"=>$code_po,"Product_description"=>$code_description,"Position"=>$pos,"Qty"=>$item_qty);
or change your code to
$new = "new_name";
$array[0][$new]=$array[0]["Order_no"];
unset($array["Order_no"]);
print_r($array);
Just be careful this would change the order of the array

Is it possible to get value from specified key in the same array?

I wonder if I can select any key inside my array, and set it as the value of another key. in order to be more clear (because my question may not clear enough), I try to do something like this:
$variable = array(
'key' => 'value',
'key2' => $variable['key']
);
As you can see, it won't work (unless I do something like: $variable['key2'] = $variable['key'] out of the array, but this is not what i'm looking for and i'll use it only if I won't be able at all to do it inside the same array).
I searched for any solution but still haven't found one...
There is any way to do such thing inside the same array?
Thank you very much
This way you can`t do it, because this key does not exist yet.
Why to store two same variables in same array? Maybe show us what you are trying to do in bigger picture, so we can help you some way.
Think of it as the code doing what is in the parenthesis FIRST. Since $variable isn't set yet, you'll get an error on $variable['key'], since $variable isn't an array yet.
You must set $variable before
See
$variable = new array();
$variable['key'] = $variable->key2 = 'value';
Also
//create array
$variable = array(
'key' => 'value'
);
//then override
$variable = array(
'key2' => $variable['key'],
'key' => 'new_value'
);

PHP Prepend two elements to associative array

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

Set array value to a value from the same array on creation PHP

I'm trying to see if you can assign an array value during creation to a value in the same array.
If I'm declaring and initializing an array like this:
$this->array = array(...);
Can I do something like this?
$this->array = array
(
'value1' => 'hello',
'value2' => $this->array['value1'],
);
I've tried it already and I get back
Notice: Undefined index: value1 in /Sites/website/config.php on line 329
I've gotten around this problem already but now out of interest I want to see if theres actually a way to do this.
It has to be during creation and declared like above, not through
$array['value1'] = 'foo';
$array['value2'] = $array['value1'];
or
$common = 'foo';
$array = array('value1' => $common, 'value2' => $common);
Is this technically impossible or is there any way?
I don't think it's possible. The array has to be parsed before it can be assigned, so at the time $this->array['value1'] is being calculated, $this->array is still null.
Basically, $this->array['value1'] cannot be be accessed before $this->array['value2'] is set, which needs to access $this->array['value1'], which cannot be accessed before . . .
The reason you're getting Notice: Undefined index: value1 in /Sites/website/config.php on line 329 is because when you're defining your array the value you're trying to access has not yet been defined because you haven't reached the end of the initial function.
In the following code:
$this->array = array
( //this is the start of the array
'value1' => 'hello',
'value2' => $this->array['value1'],
); //this is the end of the array statement.
The array is not defined until you reach the end of the statement.
The reason the other methods work is because you're using multiple steps to access an already existing variable.
I think that is not possible, assign the element when the array starts
you can set as false and before the action that set the value as your code.
example :
$common = 'foo';
$array = array(
'value1' => $common,
'value2' => $common
);
or you can use the function array_combine

Categories