Why does Referencing to Array Elements not work in this situation? - php

This referencing works:
$awesome_array = array (1,2,3);
$cool_array = array (4,5,6);
$ref = &$awesome_array; // reference awesome_array
$awesome_array = $cool_array;
echo $ref; //produces (4,5,6) as expected
This referencing also works:
$array[0] = "original";
$element_reference = &$array[0]; // reference $array[0]
$array[0] = "modified";
echo $element_reference; // returns "modified" as expected.
But referencing the elements in an array does not work when you change the entire array. How do you get around this?
$array = array (1,2,3);
$new_array = array (4,5,6);
$element_reference = &$array[0]; // reference $array[0]
$array = $new_array; // CHANGE ENTIRE ARRAY
echo $element_reference; // returns 1 despite the fact that the entire array changed. I need it to return 4?
Why does it not return 4 since the array has changed? How do you reference the element so it returns 4?

The reference is to an element in the array, and not to "an index into a variable called $array". As such, none of the references (for elements in the old array) apply to the new array.
The original references still refer to the original array, and elements therein; even if the original array is no longer immediately accessible.
To refer a particular index of a variable that resolves to an array, just use a normal index operation:
$array = array (1,2,3);
$new_array = array (4,5,6);
$i = 0;
echo $array[$i]; // -> 1
$array = $new_array; // reassign variable with new array
echo $array[$i]; // -> 4

Related

PHP - Get first and last key and value from array

From a given array (eg: $_SERVER), I need to get the first and last key and value. I was trying use array_shift to get first value and key but what I get is value.
Here is the $_SERVER array:
print_r($_SERVER, true))
And I tried with:
echo array_shift($_SERVER);
With PHP >= 7.3 you can get it fast, without modification of the array and without creating array copies:
$first_key = array_key_first($_SERVER);
$first_value = $_SERVER[$first_key];
$last_key = array_key_last($_SERVER);
$last_value = $_SERVER[$last_key];
See array_key_first and array_key_last.
It's not clear if you want the value, or the key. This is about as efficient as it gets, if memory usage is important.
If you want the key, use array_keys. If you want the value, just refer to it with the key you got from array_keys.
$count = count($_SERVER);
if ($count > 0) {
$keys = array_keys($_SERVER);
$firstKey = $keys[0];
$lastKey = $keys[$count - 1];
$firstValue = $array[$firstKey];
$lastValue = $array[$lastKey];
}
You can't use $count - 1 or 0 to get the first or last value in keyed arrays.
You can do a foreach loop, and break out after the first one:
foreach ( $_SERVER as $key => $value ) {
//Do stuff with $key and $value
break;
}
Plenty of other methods here. You can pick and choose your favorite flavor there.
Separate out keys and values in separate arrays, and extract first and last from them:
// Get all the keys in the array
$all_keys = array_keys($_SERVER);
// Get all the values in the array
$all_values = array_values($_SERVER);
// first key and value
$first_key = array_shift($all_keys);
$first_value = array_shift($all_values);
// last key and value (we dont care about the pointer for the temp created arrays)
$last_key = end($all_keys);
$last_value = end($all_values);
/* you can use reset function after end function call
if you worry about the pointer */
What about this:
$server = $_SERVER;
echo array_shift(array_values($server));
echo array_shift(array_keys($server));
reversed:
$reversed = array_reverse($server);
echo array_shift(array_values($reversed));
echo array_shift(array_keys($reversed));
I think array_slice() will do the trick for you.
<?php
$a = array_slice($_SERVER, 0, 1);
$b = array_slice($_SERVER, -1, 1, true);
//print_r($_SERVER);
print_r($a);
print_r($b);
?>
OUTPUT
Array ( [TERM] => xterm )
Array ( [argc] => 1 )
DEMO: https://3v4l.org/GhoFm

How to get the exact value of the last array index in PHP?

Currently i have an array $newArr with some elements as shown in picture below. How do I know the last digit of the array index (highlighted in yellow)?
This is important because, if later I wanted to insert a new record into this $newArr array, I could just
$newArr[$the_variable_that_holds_the_last_digit + 1] = ['foo', 'bar'];
otherwise the whole array overwrite if
$newArr = ['foo', 'bar'];
I think you are looking for end pointer
$array = array(
'a' => 1,
'b' => 2,
'c' => 3,
);
end($array); // it will point to last key
$key = key($array); // get the last key using `key`
Assuming you have the numerically indexed array, the last index on your array is :
$last_index = count($newArr) -1;
if However your keys are not sequential, you can do this:
end($newArr);
$last_key = key($newArr);
I think you can try this
$array = end($newArr);
$last_index = key($array);//Its display last key of array
For more details, please follow this link.
If the only reason is to not overwrite the values you can use [] which means add new value.
$arr = [1,2,3,4];
var_dump($arr);
// incorrect way:
$arr = [1,2];
var_dump($arr);
//correct way
$arr = [1,2,3,4];
$arr[] = [1,2];
var_dump($arr);
See here for output: https://3v4l.org/ZTg28
The "correct way" will in the example above input a new array in the array.
If you want to add only the values you need to insert them one at the time.
$arr[] = 1;
$arr[] = 2;

php to create an array with value stored in variables

well, i have 2 variables
$variable1 = "123";
$variable2 = "321";
both variables are calculated by other methods and may vary due to change of circumstances, now i want to put these values in a single array for displaying, what i want is something like this
$array = ($variable1, $variable2)
and print like(in IDE)
array([0]=>123 [1]=>321)
both 123 and 321 are representations of variable values.
i tried compact() function but it gave me something weird, i tried make these two variables an array with only one element and merge them into one array but in fact i have many variables and it's infeasible to do this for every one of them.....please show me how i can do it and explain in detail the mechanism behind it, thank you very much.
There are several ways to do what you want.
You can use one of examples below :
// Define a new array with the values
$array1 = array($variable1, $variable2);
// Or
$array2 = [$variable1, $variable2];
// Debug
print_r($array1);
print_r($array2);
// Define an array and add the values next
$array3 = array();
$array3[] = $variable1;
$array3[] = $variable2;
// Debug
print_r($array3);
// Define an array and push the values next
// http://php.net/manual/en/function.array-push.php
$array4 = array();
array_push($array4, $variable1);
array_push($array4, $variable2);
// Debug
print_r($array4);
Just use the array function to get the values into one array.
$var1 = "123";
$var2 = "321";
$array = array($var1,$var2);
var_dump($array); returns:
array (size=2)
0 => string '123' (length=3)
1 => string '321' (length=3)
Or another example on how you could do it is:
$array = array();
$array[] = myFunction(); //myFunction returns a value and by using $array[] you can add the value to the array.
$array[] = myFunction2();
var_dump($array);
Here is your answer
$variable1 = "123";
$variable2 = "321";
$arr =array();
array_push($arr,$variable1);
array_push($arr,$variable2);
echo '<pre>';
print_r($arr);
Hope this will solve your problem.
As you want to put these item in array
First you have to initialize a variable
$newArray = []
After that you have to store the value in array which can be done by this
$newArray[] = $variable1;
// OR BY
array_push($newArray, $variable1);
They both are same it push the data to the end of the array
So your code will be like this
$newArray = []
$newArray[] = $variable1;
$newArray[] = $variable2;
If you want to do it in loop then do somthing like this
$newArray = []
foreach($values as $value){
$newArray[] = $value;
}
If there is a fix value then you can do like this
$newArray = [$variable1, $variable2];
//OR BY
$newArray = array($variable1, $variable2);
Both are same
And to print the value use
print_r($newArray);
Hope this will help

Php merge object array getting wrongly only merge last values

I am trying to merge an object as follows from set of values which comes from database as follows:
$pooldetails = array();
$qstncount = 5;
for($i=0;$i<$qstncount;$i++){
$stdClass = $DB->get_record_sql("SELECT * FROM {pool_objective} po WHERE (po.id = $randarray[$i])");
$pooldetails = (object) array_merge((array) $pooldetails, (array) $stdClass);
}
When I print outside as follows:
print_r($pooldetails);
I am getting only last value in this array. I mean the value of $qstncoun=4 .First 4 values are missing.What I am doing wrong?
It's expected actually. Quoting the docs:
If the input arrays have the same string keys, then the later value
for that key will overwrite the previous one.
To get the results combined, use array_merge_recursive() instead:
$arr1 = ['a' => 1];
$arr2 = ['a' => 2];
var_dump(array_merge($arr1, $arr2));
// ['a' => 2]
var_dump(array_merge_recursive($arr1, $arr2));
// ['a' => [1, 2]]
Be aware, however, of the following:
If the input arrays have the same string keys, then the values for
these keys are merged together into an array, and this is done
recursively, so that if one of the values is an array itself, the
function will merge it with a corresponding entry in another array
too. If, however, the arrays have the same numeric key, the later
value will not overwrite the original value, but will be appended.
It probably doesn't matter in your case, however, as keys map to column names. So you can use something like...
$pooldetails = array();
$qstncount = 5;
for($i=0;$i<$qstncount;$i++){
$stdClass = $DB->get_record_sql("SELECT * FROM {pool_objective} po WHERE (po.id = $randarray[$i])");
$pooldetails = array_merge_recursive($pooldetails, (array) $stdClass);
}
$pooldetails = (object) $pooldetails;

get first and last element in array

hey there i have this array:
array(1) {
["dump"]=>
string(38) "["24.0",24.1,24.2,24.3,24.4,24.5,24.6]"
}
my question:
how to get the first and the last element out from this array, so i will have:
$firstEle = "24.0";
and
$lastEle = "24.6";
anybody knows how to get those elements from the array?
i already tried this:
$arr = json_decode($_POST["dump"], true);
$col0 = $arr[0];
$col1 = $arr[1];
$col2 = $arr[2];
$col3 = $arr[3];
$col4 = $arr[4];
$col5 = $arr[5];
$col6 = $arr[6];
i could chose $col0 and $col6, but the array could be much longer, so need a way to filter the first("24.0") and the last("24.6") element.
greetings
reset() and end() does exactly this.
From the manual:
reset(): Returns the value of the first array element, or FALSE if the array is empty.
end(): Returns the value of the last element or FALSE for empty array.
Example:
<?php
$array = array(24.0,24.1,24.2,24.3,24.4,24.5,24.6);
$first = reset($array);
$last = end($array);
var_dump($first, $last);
?>
Which outputs:
float(24)
float(24.6)
DEMO
NOTE: This will reset your array pointer meaning if you use current() to get the current element or you've seeked into the middle of the array, reset() and end() will reset the array pointer (to the beginning and to the end):
<?php
$array = array(30.0, 24.0, 24.1, 24.2, 24.3, 24.4, 24.5, 24.6, 12.0);
// reset — Set the internal pointer of an array to its first element
$first = reset($array);
var_dump($first); // float(30)
var_dump(current($array)); // float(30)
// end — Set the internal pointer of an array to its last element
$last = end($array);
var_dump($last); // float(12)
var_dump(current($array)); // float(12) - this is no longer 30 - now it's 12
You can accessing array elements always with square bracket syntax. So to get the first use 0, as arrays are zero-based indexed and count($arr) - 1 to get the last item.
$firstEle = $arr[0];
$lastEle = $arr[count($arr) - 1];
As of PHP 7.3, array_key_first and array_key_last is available
$first = $array[array_key_first($array)];
$last = $array[array_key_last($array)];
You can use reset() to get the first:
$firstEle = reset($arr);
reset() rewinds array's internal pointer to the first element and returns the value of the first array element.
And end() to get the last:
$lastEle = end($arr);
end() advances array's internal pointer to the last element, and returns its value.
For first element: current($arrayname);
For last element: end($arrayname);
current(): The current() function returns the value of the current
element in an array. Every array has an internal pointer to its
"current" element, which is initialized to the first element inserted
into the array.
end(): The end() function moves the internal pointer to, and outputs,
the last element in the array. Related methods: current() - returns
the value of the current element in an array
$array = array(24.0,24.1,24.2,24.3,24.4,24.5,24.6);
$first = current($array);
$last = end($array);
echo 'First Element: '.$first.' :: Last Element:'.$last;
Output result:
First Element: 24 :: Last Element:24.6
We can acheive the goal using array values and array key also
Example : Array Values
<?php
$array = array(24.0,24.1,24.2,24.3,24.4,24.5,24.6);
$array_values = array_values($array);
// get the first item in the array
print array_shift($array_values);
// get the last item in the array
print array_pop($array_values);
?>
Example : Array Keys
<?php
$array = array(24.0,24.1,24.2,24.3,24.4,24.5,24.6);
$array_keys = array_keys($array);
// get the first item in the array
print $array[array_shift($array_keys)];
// get the last item in the array
print $array[array_pop($array_keys)];
?>

Categories