$arr = array('a' => 1, 'b' => 2);
$xxx = &$arr['a'];
unset($xxx);
print_r($arr); // still there :(
so unset only breaks the reference...
Do you know a way to unset the element in the referenced array?
Yes, I know I could just use unset($arr['a']) in the code above, but this is only possible when I know exactly how many items has the array, and unfortunately I don't.
This question is kind of related to this one (this is the reason why that solution doesn't work)
I may be wrong but I think the only way to unset the element in the array would be to look up the index that matches the value referenced by the variable you have, then unsetting that element.
$arr = array('a' => 1, 'b' => 2);
$xxx = &$arr['a'];
$keyToUnset = null;
foreach($arr as $key => $value)
{
if($value === $xxx)
{
$keyToUnset = $key;
break;
}
}
if($keyToUnset !== null)
unset($arr[$keyToUnset]);
$unset($xxx);
Well, anyway, something along those lines. However, keep in mind that this is not super efficient because each time you need to unset an element you have to iterate over the full array looking for it.
Assuming you have control over how $xxx is used, you may want to consider using it to hold the key in the array, instead of a reference to the element at the key. That way you wouldn't need to search the array when you wanted to unset the element. But you would have to replace all sites that use $xxx with an array dereference:
$arr = array('a' => 1, 'b' => 2);
$xxx = 'a';
// instead of $xxx, use:
$arr[$xxx];
// to unset, simply
unset($arr[$xxx]);
When you unset the reference, you just break the binding between variable name and variable content. This does not mean that variable content will be destroyed.
And with respect to the code above - I do not think there is need in separate key
foreach($arr as $key => $value)
{
if($value === $xxx)
{
unset($arr[$key]);
break;
}
}
The simple answer:
$arr = array('a' => 1, 'b' => 2);
$xxx = 'a';
unset($arr[$xxx]);
print_r($arr); // gone :)
i.e.. You probably don't ever really need a reference. Just set $xxx to the appropriate key.
Related
I have an array like:
$array = array('foo' => 'bar', 33 => 'bin', 'lorem' => 'ipsum');
echo native_function($array, 0); // bar
echo native_function($array, 1); // bin
echo native_function($array, 2); // ipsum
So, this native function would return a value based on a numeric index (second arg), ignoring assoc keys, looking for the real position in array.
Are there any native function to do that in PHP or should I write it?
Thanks
$array = array('foo' => 'bar', 33 => 'bin', 'lorem' => 'ipsum');
$array = array_values($array);
echo $array[0]; //bar
echo $array[1]; //bin
echo $array[2]; //ipsum
array_values() will do pretty much what you want:
$numeric_indexed_array = array_values($your_array);
// $numeric_indexed_array = array('bar', 'bin', 'ipsum');
print($numeric_indexed_array[0]); // bar
I am proposing my idea about it against any disadvantages array_values( ) function, because I think that is not a direct get function.
In this way it have to create a copy of the values numerically indexed array and then access. If PHP does not hide a method that automatically translates an integer in the position of the desired element, maybe a slightly better solution might consist of a function that runs the array with a counter until it leads to the desired position, then return the element reached.
So the work would be optimized for very large array of sizes, since the algorithm would be best performing indices for small, stopping immediately. In the solution highlighted of array_values( ), however, it has to do with a cycle flowing through the whole array, even if, for e.g., I have to access $ array [1].
function array_get_by_index($index, $array) {
$i=0;
foreach ($array as $value) {
if($i==$index) {
return $value;
}
$i++;
}
// may be $index exceedes size of $array. In this case NULL is returned.
return NULL;
}
Yes, for scalar values, a combination of implode and array_slice will do:
$bar = implode(array_slice($array, 0, 1));
$bin = implode(array_slice($array, 1, 1));
$ipsum = implode(array_slice($array, 2, 1));
Or mix it up with array_values and list (thanks #nikic) so that it works with all types of values:
list($bar) = array_values(array_slice($array, 0, 1));
I'm working with an array of data that I've changed the names of some array keys, but I want the data to stay the same basically... Basically I want to be able to keep the data that's in the array stored in the DB, but I want to update the array key names associated with it.
Previously the array would have looked like this: $var_opts['services'] = array('foo-1', 'foo-2', 'foo-3', 'foo-4');
Now the array keys are no longer prefixed with "foo", but rather with "bar" instead. So how can I update the array variable to get rid of the "foos" and replace with "bars" instead?
Like so: $var_opts['services'] = array('bar-1', 'bar-2', 'bar-3', 'bar-4');
I'm already using if(isset($var_opts['services']['foo-1'])) { unset($var_opts['services']['foo-1']); } to get rid of the foos... I just need to figure out how to replace each foo with a bar.
I thought I would use str_replace on the whole array, but to my dismay it only works on strings (go figure, heh) and not arrays.
The idea:
Get a list of all your array keys
Modify each one of them as you choose
Replace the existing keys with the modified ones
The code:
$keys = array_keys($arr);
$values = array_values($arr);
$new_keys = str_replace('foo', 'bar', $keys);
$arr = array_combine($new_keys, $values);
What this actually does is create a new array which has the same values as your original array, but in which the keys have been changed.
Edit: updated as per Kamil's comment below.
For the values you've provided
$var_opts['services'] = array('foo-1', 'foo-2', 'foo-3', 'foo-4');
var_dump($var_opts['services']);
foreach($var_opts['services'] as &$val) {
$val = str_replace('foo', 'bar', $val);
}
unset($val);
var_dump($var_opts['services']);
or if you want to change the actual keys
$var_opts['services'] = array('foo-1' => 1, 'foo-2' => 2, 'foo-3' => 3, 'foo-4' => 4);
var_dump($var_opts['services']);
foreach($var_opts['services'] as $i => $val) {
unset($var_opts['services'][$i]);
$i = str_replace('foo', 'bar', $i);
$var_opts['services'][$i] = $val;
}
var_dump($var_opts['services']);
I have an array:
$arr = array('foo', 'bar', 'bash', 'monkey', 'badger');
I want to have the elements in that array appear as the variables in my list():
list($foo, $bar, $bash, $monkey, $badger) = $data;
Without actually specifying the variables, I tried;
list(implode(",$", $arr)) = $data; and
list(extract($arr)) = $data;
But they don't work, I get:
Fatal error: Can't use function return value in write context
Does anyone have any idea whether this is possible?
UPDATE: more context:
I am getting a CSV of data from an API, the first row is column names, each subsequent row is data. I want to build an associative array that looks like this:
$data[0]['colname1'] = 'col1data';
$data[0]['colname2'] = 'col2data';
$data[0]['colname3'] = 'col3data';
$data[1]['colname1'] = 'col1data';
$data[1]['colname2'] = 'col2data';
$data[1]['colname3'] = 'col3data';
Before I do that, however, I want to make sure I have all the columns I need. So, I build an array with the column names I require, run some checks to ensure the CSV does contain all the columns I need. Once thats done, the code looks somewhat like this (which is executed on a foreach() for each row of data in the CSV):
//$data is an array of data WITHOUT string indexes
list( $col1,
$col2,
$col3,
...
$col14
) = $data;
foreach($colNames AS $name)
{
$newData[$i][$name] = $$name;
}
// Increemnt
$i++;
As I already HAVE an array of column name, I though it would save some time to use THAT in the list function, instead of explicitly putting in each variable name.
The data is cleaned and sanitised elsewhere.
Cheers,
Mike
I want to have the elements in that array appear as the variables in my list():
i think there is your problem in understanding. list() does not create a new list structure or variable, it can only be used to assign many variables at once:
$arr = array(1, 2, 3);
list($first, $second, $third) = $arr;
// $first = 1, $second = 2, $third = 3
see http://php.net/list for more information.
you are probably looking for an associative array. you can create it with the following code:
$arr = array('first' => 1, 'second' => 2, 'third' => 3);
// $arr['first'] = 1, …
If some rows in your input file are missing columns, you can't really know which one is missing. Counting the number of values and aborting or jumping to next row when less than expected should be enough.
... unless you set the rule that last columns are optional. I'll elaborate on this.
Your code sample is far for complete but it seems that your problem is that you are using arrays everywhere except when matching column names to cell values. Use arrays as well: you don't need individual variables and they only make it harder. This is one of the possible approaches, not necessarily the best one but (I hope) clear enough:
<?php
$required_columns = array('name', 'age', 'height');
$input_data = array(
array('John', 33, 169),
array('Bill', 40, 180),
array('Ashley', 21, 155),
array('Vincent', 13), // Incomplete record
array('Michael', 55, 182),
);
$output = array();
foreach($input_data as $row_index => $row){
foreach($required_columns as $col_index => $column_name){
if( isset($row[$col_index]) ){
$output[$row_index][$column_name] = $row[$col_index];
}
}
}
print_r($output);
?>
I've used $row_index and $col_index for simplicity.
Original answer, for historical purposes only ;-)
I can't really understand your specs but PHP features variable variables:
<?php
$arr = array('foo', 'bar', 'bash', 'monkey', 'badger');
foreach($arr as $i){
$$i = $i;
}
?>
Now your script has these variables available: $foo, $bar... It's quite useless and potentially dangerous but it does what you seem to need.
You are trying to use a language construct in a manner in which it's not meant to be used. Use variable variables as Alvaro mentioned.
$arr = array('foo', 'bar', 'bash', 'monkey', 'badger');
foreach ($arr as $index => $key) {
$$key = $data[$index];
}
or
$arr = array('foo', 'bar', 'bash', 'monkey', 'badger');
$result = array();
foreach ($arr as $index => $key) {
$result[$key] = $data[$index];
}
extract($result);
In short, do not use "list", use arrays and associated arrays. Write helper functions to make your code clearer.
why not immediatly call the vars like
$arr['foo']
or
$arr[0]
If you want to extract the elements of $data into the current context, you can do that with extract. You might find it useful to call array_intersect_key first to pare down $data to the elements that you want to extract.
May be try like this :
$arr = array('foo', 'bar', 'bash', 'monkey', 'badger');
$data = "$".implode(",", $arr);
echo str_replace(",", ",$", $data);
I've created this method to change every value in an array. I'm kinda new to PHP, so I think there should be a more efficient way to do this.
Here's my code:
foreach($my_array as $key => $value)
{
$my_array[$key] = htmlentities($value);
}
Is there a better way to do this?
Thank you in advance.
You'd probably be better off with array_map
$my_array = array_map( 'htmlentities' , $my_array);
You can reference the array and change it
foreach ($array as &$value) {
$value = $value * 2;
}
When you need to apply a function to the value and reassign it to the value, Galen's answer is a good solution. You could also use array_walk(), although it doesn't read as easily as a nice, simple loop.
When you only need to assign, for example, a primitive value to each element in the array, the following will work.
If your keys are numeric, you can use array_fill():
array_fill(0, sizeof($my_array), "test");
If you're using an associative array, you can probably use array_fill_keys(), with something like:
array_fill_keys(array_keys($my_array), "test");
If you mark $value as a reference (&$value) any change you make on $value will effect the corresponding element in $my_array.
foreach($my_array as $key => &$value)
{
$value = "test";
}
e.g.
$my_array = array(1,2,3,4,5,6);
foreach($my_array as &$value)
{
$value *= 5;
}
echo join($my_array, ', ');
prints
5, 10, 15, 20, 25, 30
(And there's also array_map() if you want to keep the original array.)
foreach($my_array as &$value)
{
$value = "test";
}
You could use array_fill, starting at 0 and going to length count($my_array). Not sure if it's better though.
Edit: Rob Hruska's array_fill_keys code is probably better depending on what you define as better (speed, standards, readability etc).
Edit2: Since you've now edited your question, these options are now no longer appropriate as you require the original value to be modified, not changed entirely.
If I had an array like:
$array['foo'] = 400;
$array['bar'] = 'xyz';
And I wanted to get the first item out of that array without knowing the key for it, how would I do that? Is there a function for this?
reset() gives you the first value of the array if you have an element inside the array:
$value = reset($array);
It also gives you FALSE in case the array is empty.
PHP < 7.3
If you don't know enough about the array (you're not sure whether the first key is foo or bar) then the array might well also be, maybe, empty.
So it would be best to check, especially if there is the chance that the returned value might be the boolean FALSE:
$value = empty($arr) ? $default : reset($arr);
The above code uses reset and so has side effects (it resets the internal pointer of the array), so you might prefer using array_slice to quickly access a copy of the first element of the array:
$value = $default;
foreach(array_slice($arr, 0, 1) as $value);
Assuming you want to get both the key and the value separately, you need to add the fourth parameter to array_slice:
foreach(array_slice($arr, 0, 1, true) as $key => $value);
To get the first item as a pair (key => value):
$item = array_slice($arr, 0, 1, true);
Simple modification to get the last item, key and value separately:
foreach(array_slice($arr, -1, 1, true) as $key => $value);
performance
If the array is not really big, you don't actually need array_slice and can rather get a copy of the whole keys array, then get the first item:
$key = count($arr) ? array_keys($arr)[0] : null;
If you have a very big array, though, the call to array_keys will require significant time and memory more than array_slice (both functions walk the array, but the latter terminates as soon as it has gathered the required number of items - which is one).
A notable exception is when you have the first key which points to a very large and convoluted object. In that case array_slice will duplicate that first large object, while array_keys will only grab the keys.
PHP 7.3+
PHP 7.3 onwards implements array_key_first() as well as array_key_last(). These are explicitly provided to access first and last keys efficiently without resetting the array's internal state as a side effect.
So since PHP 7.3 the first value of $array may be accessed with
$array[array_key_first($array)];
You still had better check that the array is not empty though, or you will get an error:
$firstKey = array_key_first($array);
if (null === $firstKey) {
$value = "Array is empty"; // An error should be handled here
} else {
$value = $array[$firstKey];
}
Fake loop that breaks on the first iteration:
$key = $value = NULL;
foreach ($array as $key => $value) {
break;
}
echo "$key = $value\n";
Or use each() (warning: deprecated as of PHP 7.2.0):
reset($array);
list($key, $value) = each($array);
echo "$key = $value\n";
There's a few options. array_shift() will return the first element, but it will also remove the first element from the array.
$first = array_shift($array);
current() will return the value of the array that its internal memory pointer is pointing to, which is the first element by default.
$first = current($array);
If you want to make sure that it is pointing to the first element, you can always use reset().
reset($array);
$first = current($array);
another easy and simple way to do it use array_values
array_values($array)[0]
Just so that we have some other options: reset($arr); good enough if you're not trying to keep the array pointer in place, and with very large arrays it incurs an minimal amount of overhead. That said, there are some problems with it:
$arr = array(1,2);
current($arr); // 1
next($arr); // 2
current($arr); // 2
reset($arr); // 1
current($arr); // 1 !This was 2 before! We've changed the array's pointer.
The way to do this without changing the pointer:
$arr[reset(array_keys($arr))]; // OR
reset(array_values($arr));
The benefit of $arr[reset(array_keys($arr))]; is that it raises an warning if the array is actually empty.
Test if the a variable is an array before getting the first element. When dynamically creating the array if it is set to null you get an error.
For Example:
if(is_array($array))
{
reset($array);
$first = key($array);
}
We can do
$first = reset($array);
Instead of
reset($array);
$first = current($array);
As reset()
returns the first element of the array after reset;
You can make:
$values = array_values($array);
echo $values[0];
Use reset() function to get the first item out of that array without knowing the key for it like this.
$value = array('foo' => 400, 'bar' => 'xyz');
echo reset($value);
output //
400
Starting with PHP 7.3.0 it's possible to do without resetting the internal pointer. You would use array_key_first. If you're sure that your array has values it in then you can just do:
$first = $array[array_key_first($array)];
More likely, you'll want to handle the case where the array is empty:
$first = (empty($array)) ? $default : $array[array_key_first($array)];
You can try this.
To get first value of the array :-
<?php
$large_array = array('foo' => 'bar', 'hello' => 'world');
var_dump(current($large_array));
?>
To get the first key of the array
<?php
$large_array = array('foo' => 'bar', 'hello' => 'world');
$large_array_keys = array_keys($large_array);
var_dump(array_shift($large_array_keys));
?>
In one line:
$array['foo'] = 400;
$array['bar'] = 'xyz';
echo 'First value= ' . $array[array_keys($array)[0]];
Expanded:
$keys = array_keys($array);
$key = $keys[0];
$value = $array[$key];
echo 'First value = ' . $value;
You could use array_values
$firstValue = array_values($array)[0];
You could use array_shift
I do this to get the first and last value. This works with more values too.
$a = array(
'foo' => 400,
'bar' => 'xyz',
);
$first = current($a); //400
$last = end($a); //xyz