I want to output some information to an array from a multidimensional one referenced like this:
$adam_brown[$climbing][$punk]['woodwork'][1]['ID']
$adam_brown[$climbing][$punk]['cheese'][1]['Name']
$adam_brown[$climbing][$punk]['ruffian'][1]['ID']
This part will always be the same, so could I create a shorter, maybe one letter reference to it, e.g.:
$a = $adam_brown[$climbing][$punk]
Otherwise I am needlessly writing the same information several times
Then I could reference the above info like this:
$a['woodwork'][1]['ID']
If you want to make a shorthand to the $adam_brown[$climbing][$punk], just do it as you wrote:
$a = $adam_brown[$climbing][$punk];
However if you want to be able to modify the original array, you have tu use & reference:
$a = &$adam_brown[$climbing][$punk];
Documentation: Returning References
Simply use
$a = &$adam_brown[$climbing][$punk];
Related
I want to convert two different PHP tags into a single PHP tag.This may sound a little weird but recently I found a question like this and answer with correct marked.
I can't find I'm currently lost address.
My question:
for example;
$gates = array('t1','t2','t3',t4','t5');
$openGates-> and $gates merge.
Result:
$openGates->t1; or t2,t3.
If I remember correctly, the answer to the problem I found before was;
$openGates->{$gates}; like this. I not sure
How can I do that?
You seem to be confusing objects with arrays. Arrays simply contain data, unless you create them with keys also. Such as:
$gates = array('t1'=>true,'t2'=>false,'t3'=>"maybe",'t4'=>0,'t5'=>50);
Matthew Page is correct in that you should look up PHP OOP for a solution.
That being said, you can cast your array to an object providing it has both keys and values:
$gates = (object) array('t1'=>true,'t2'=>false,'t3'=>"maybe",'t4'=>0,'t5'=>50);
or
$openGates = (object) $gates;
This will allow you to access 'properties' of the object in the way you have demonstrated:
echo $openGates->t1;, for example. The -> operator only applies to objects, which are instances of classes, not arrays.
If you do cast your array to the type of object, be sure that you have both keys and values.
It's not simple for newbie programmer...
At first:
$gates = array('t1','t2','t3','t4','t5');
It's Array
$openGates->
This is class instance. Btw. You can retrieve class instance var like $className->varName
You can't simple merge array and class instance. But you can create new class instance variables by loop.
foreach($gates as $gateKey=>$gateVal) {
$openGates->$gatesVal = NULL;
}
But I think it's, in result should be like that:
$gates = array('t1'=>'opened','t2'=>'closed','t3'=>'closed','t4'=>'opened','t5'=>'opened');
foreach($gates as $gateKey=>$gateVal) {
$openGates->$gateKey = $gateVal;
}
echo $openGates->t1;
// or
foreach($gates as $key=>$val) {
echo $openGates->$key.PHP_EOL;
}
Btw you can simple set $openGates->gates = $gates; and call it like echo $openGates->gates['t1'];
There exists such:
$var1 = $var2 = "blabla";
but is there a way to set similar inside array? like:
array(
'key1'='key2' => "blabla",
...................
)
p.s. I dont need outside of array functions, like array_fill_keys or etc.. I want inside-array solution (if it exists).
You can set multiple array values of an array like this. Perhaps it even works without the first line.
$a = array();
$a['key1'] = $a['key2'] = 'blablabla';
Or initialize the desired keys using this awkward syntax:
$a = array_fill_keys(array('key1', 'key2'), 'blablabla');
Although the second one works, I wouldn't use it. Better to use a couple of characters extra or even separate lines than to write such a weird line which doesn't have much benefit apart from saving a tiny bit of code.
Bear with me, I'm learning.
I often see snippets like the one below:
<?p
$imageArray = get_field('image_field');
$imageAlt = $imageArray['alt'];
$imageURL = $imageArray['url'];
?>
It is pedagogical and clear and organized. But is it necessary to get the entire array before querying the array for values? Can I not define the variable in just a single line? Something like the below (which doesn't work, neither the other variants I have tried):
$imageAlt = get_field('image_field', ['alt']);
$imageURL = get_field('image_field', ['url']);
Yes, you can.
As of PHP 5.4 it is possible to array dereference the result of a function or method call directly. Before it was only possible using a temporary variable. - Source
$imageAlt = get_field('image_field')['alt'];
https://eval.in/548036
The question you are asking can be answered by asking 2 questions:
Is it doable ?
Is it a good idea to do it that way ?
Is it doable ?
Yes! You do not have to store the array in a variable and re-use it later.
For instance, you could do:
$imageAlt = get_field('image_field')['alt'];
Note: This will work in PHP 5.4+ and is called: Array dereferencing.
But that is not the only consideration...
Is it a good idea to do it that way ?
No. It's not a good idea in many cases. The get_field() function, depending on your context, is probably doing a lot of work and, each time you call it, the same work is don multiple times.
Let's say you use the count() function. It will count the number of items in an array. To do that, it must iterate through all items to get the value.
If you use the count() function each time you need to validate number of items in an array, you are doing the task of counting each and every time. If you have 10 items in your array, you probably won't notice. But if you have thousands of items in your array, this may cause a delay problem to compute your code (a.k.a. it will be slow).
That is why you would want to do something like: $count = count($myArray); and use a variable instead of calling the function.
The same applies to your question.
While PHP 5.4+ allows you to directly dereference a function return value like this:
get_field('image_field')['alt']
...in this particular case I would not suggest you do so, since you're using two values from the resulting array. A function call has a certain overhead just in itself, and additionally you don't know what the function does behind the scenes before it returns a result. If you call the function twice, you may incur a ton of unnecessary work, where a single function call would have done just as well.
This is not to mention keeping your code DRY; if you need to change the particulars of the function call, you now need to change it twice...
PHP allows you to play around quite a bit:
function foo(){
return array('foo' => 1, 'bar' => 2);
}
Option 1
echo foo()['foo']; // 1
# Better do this if you plan to reuse the array value.
echo ($tmp = foo())['foo']; // 1
echo $tmp['bar']; // 2
It is not recommended to call a function that returns an array, to specifically fetch 1 key and on the next line doing the same thing.
So it is better to store the result of the function in a variable so you can use it afterwards.
Option 2
list($foo, $bar) = array_values(foo());
#foo is the first element of the array, and sets in $foo.
#bar is the second element, and will be set in $bar.
#This behavior is in PHP 7, previously it was ordered from right to left.
echo $foo, $bar; // 12
Option 3
extract(foo()); // Creates variable from the array keys.
echo $foo, $bar;
extract(get_field('image_field'));
echo $alt, $url;
Find more information on the list constructor and extract function.
i know this
$var1 = "10";
$var2 = "var1";
then
echo $$var2 gives us 10
i want to this with array
i have array
$intake_arr = array(5=>10,7=>20,8=>30,9=>40,10=>50,11=>60,12=>70);
i have some logic that will pick one array from set of array , all array will look like $intake_arr
if i do this $target_arr = "intake_arr";
then can $$target_arr[5] will yield 10? i tried but i didnt that 10 value, how can i achieve this with array
Your statement ($$target_arr[5]) is ambiguous. PHP doesn't know what you actually want to say: Do you mean: use $target_arr[5]'s value and prepend the $, to use that as a variable, or do you want to use the value of $target_arr, and get the fifth element of that array?
Obviously it's the latter, but PHP doesn't know that. In order to disambiguate your statement, you have to use curly braces:
${$target_arr}[5];
That'll yield 10. See the manual on variable variables for details
Note:
As people said in comments, and deleted answers: variable variables, like the one you're using is risky business. 9/10 it can, and indeed should be avoided. It makes your code harder to read, more error prone and, in combination with the those two major disadvantages, this is the killer: it makes your code incredibly hard to debug.
If this is just a technical exercise, consider this note a piece of friendly advice. If you've gotten this from some sort of tutorial/blog or other type of online resource: never visit that site again.
If you're actually working on a piece of code, and you've decided to tackle a specific problem using variable vars, then perhaps post your code on code-review, and let me know, I'll have a look and try to offer some constructive criticism to help you on your way, towards a better solution.
Since what you're actually trying to do is copying an array into another variable, then that's quite easy. PHP offers a variety of ways to do that:
Copy by assignment:
PHP copies arrays on assignment, by default, so that means that:
$someArray = range(1,10);//[1,2,3,4,5,6,7,8,9,10]
$foo = $someArray;
Assigns a copy of $someArray to the variable $foo:
echo $foo[0], ' === ', $someArray[0];//echoes 1 === 1
$foo[0] += 123;
echo $foo[0], ' != ', $someArray[0];//echoes 123 != 1
I can change the value of one of the array's elements without that affecting the original array, because it was copied.
There is a risk to this, as you start working with JSON encoded data, chances are that you'll end up with something like:
$obj = json_decode($string);
echo get_class($obj));//echoes stdClass, you have an object
Objects are, by default, passed and assigned by reference, which means that:
$obj = new stdClass;
$obj->some_property = 'foobar';
$foo = $obj;
$foo->some_property .= '2';
echo $obj->some_property;//echoes foobar2!
Change a property through $foo, and the $obj object will change, too. Simply because they both reference exactly the same object.
Slice the array:
A more common way for front-end developers (mainly, I think, stemming from a JS habbit) is to use array_slice, which guarantees to return a copy of the array. with the added perk that you can specify how many of the elements you'll be needing in your copy:
$someArray = range(1,100);//"large" array
$foo = array_slice($someArray, 0);//copy from index 0 to the end
$bar = array_slice($someArray, -10);//copy last 10 elements
$chunk = array_slice($someArray, 20, 4);//start at index 20, copy 4 elements
If you don't want to copy the array, but rather extract a section out of the original you can splice the array (as in split + slice):
$extract = array_splice($someArray, 0, 10);
echo count($someArray);//echoes 90
This removes the first 10 elements from the original array, and assigns them to $extract
Spend some time browsing the countless (well, about a hundred) array functions PHP offers.
${$target_arr}[5]
PHP: Variable variables
Try this one:
$intake_arr = array(5=>10,7=>20,8=>30,9=>40,10=>50,11=>60,12=>70);
$target_arr = 'intake_arr';
print ${$target_arr}[5]; //it gives 10
For a simple variable, braces are optional.But when you will use a array element, you must use braces; e.g.: ${$target_arr}[5];.As a standard, braces are used if variable interpolation is used, instead of concatenation.Generally variable interpolation is slow, but concatenation may also be slower if you have too many variables to concatenate.Take a look here for php variable variables http://php.net/manual/en/language.variables.variable.php
I was looking through some inherited PHP code when I found the following:
$emails=array();
foreach($usrs as $usr){
$emails[]=$usr['email'];
}
It's clear that this is trying to extract the 'email' property of each object in a list of users and hold them in an array. That's what I want it to do. Does this do that? I've never seen such a thing work this way. I replaced it with
array_push($emails, $usr['email']);
since I know that that does what I intend it to.
The two are the same, almost.
It will add an item to the end of the array, just as array_push does. The only difference is array_push returns the new number of elements in the array. The empty bracket notation does not return anything, obviously.
You should get comfortable with this notation, it's easier to type and read.
array_push on PHP docs mentions the use of this notation and covers two other differences as well.
Note: If you use array_push() to add one element to the array it's better to use $array[] = because in that way there is no overhead of calling a function.
Note: array_push() will raise a warning if the first argument is not an array. This differs from the $var[] behaviour where a new array is created.
When you want to push multiple elements to an array, then you could use array_push.
array_push($emails, $var1, $var2, $var3, ...);
Otherwise, if you only push one elements to an array, just use:
$emails[] = $var;
which saves you one function call.
Yes, it does the same thing. Assigning to $array[] is equivalent to pushing an element to $array.
Also, it looks prettier, so use it ;)