Populating PHP list() with values in an array - php

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

Related

How to count and output variables named in a specific numeric pattern

I have created few different strings with similar names, and I would like to display them all.
However, I will need to do this dynamically, because I will adding more of them, later on.
These strings are called:
$group1
$group2
$group3
$group4
My idea is to somehow count them all, and then display them with for loop. I just need help with counting part.
Though arrays are definitely the superior and appropriate solution in this case, since you insist in the comments that separate variables are required, you can solve this using a while loop to check for the existence of such consecutively named variables, creating the variable names dynamically with {}.
For example:
$group1 = '123';
$group2 = '456';
$group3 = '789';
$i=1;
while ($string = ${'group'.$i}) {
echo $string;
$i++;
}
Note how ${'group'.$i} dynamically creates each variable name. Also, naturally this approach would fail if the variables are not named consecutively (e.g. if you have $group1 followed by $group3). As said, you should definitely use an array for this.
See a live demo
Associative arrays are designed exactly for this:
$arr = array(
"group1" => "string1",
"group2" => "string2",
"group3" => "string3",
"group4" => "string4",
);
Now to get the length of your array:
$num = count($arr);
To access the first element
$firstElement = $arr["group1"];
Alternatively you can use an indexed array (access elements by their position):
$arr = array("string1", "string2", "string3", "string4");
$firstElement = $arr[0];
$num = count($arr);
you can use this to count+loop
$arr=array();
$add_to=array_push($arr,$group1);
$add_to=array_push($arr,$group2);
$add_to=array_push($arr,$group3);
$add_to=array_push($arr,$group4);
//count
echo count($arr);
//loop
foreach($arr as $key=>$value){
echo $value;
}

Unsetting referenced array items

$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.

PHP - Get array value with a numeric index

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

Using PHP remove duplicates from an array without using any in- built functions?

Lets say I have an array as follows :
$sampArray = array (1,4,2,1,6,4,9,7,2,9)
I want to remove all the duplicates from this array, so the result should be as follows:
$resultArray = array(1,4,2,6,9,7)
But here is the catch!!! I don't want to use any PHP in built functions like array_unique().
How would you do it ? :)
Here is a simple O(n)-time solution:
$uniqueme = array();
foreach ($array as $key => $value) {
$uniqueme[$value] = $key;
}
$final = array();
foreach ($uniqueme as $key => $value) {
$final[] = $key;
}
You cannot have duplicate keys, and this will retain the order.
A serious (working) answer:
$inputArray = array(1, 4, 2, 1, 6, 4, 9, 7, 2, 9);
$outputArray = array();
foreach($inputArray as $inputArrayItem) {
foreach($outputArray as $outputArrayItem) {
if($inputArrayItem == $outputArrayItem) {
continue 2;
}
}
$outputArray[] = $inputArrayItem;
}
print_r($outputArray);
This depends on the operations you have available.
If all you have to detect duplicates is a function that takes two elements and tells if they are equal (one example will be the == operation in PHP), then you must compare every new element with all the non-duplicates you have found before. The solution will be quadratic, in the worst case (there are no duplicates), you need to do (1/2)(n*(n+1)) comparisons.
If your arrays can have any kind of value, this is more or less the only solution available (see below).
If you have a total order for your values, you can sort the array (n*log(n)) and then eliminate consecutive duplicates (linear). Note that you cannot use the <, >, etc. operators from PHP, they do not introduce a total order. Unfortunately, array_unique does this, and it can fail because of that.
If you have a hash function that you can apply to your values, than you can do it in average linear time with a hash table (which is the data structure behind an array). See
tandu's answer.
Edit2: The versions below use a hashmap to determine if a value already exists. In case this is not possible, here is another variant that safely works with all PHP values and does a strict comparison (Demo):
$array = array (1,4,2,1,6,4,9,7,2,9);
$unique = function($a)
{
$u = array();
foreach($a as $v)
{
foreach($u as $vu)
if ($vu===$v) continue 2
;
$u[] = $v;
}
return $u;
};
var_dump($unique($array)); # array(1,4,2,6,9,7)
Edit: Same version as below, but w/o build in functions, only language constructs (Demo):
$array = array (1,4,2,1,6,4,9,7,2,9);
$unique = array();
foreach($array as $v)
isset($k[$v]) || ($k[$v]=1) && $unique[] = $v;
var_dump($unique); # array(1,4,2,6,9,7)
And in case you don't want to have the temporary arrays spread around, here is a variant with an anonymous function:
$array = array (1,4,2,1,6,4,9,7,2,9);
$unique = function($a) /* similar as above but more expressive ... ... you have been warned: */ {for($v=reset($a);$v&&(isset($k[$v])||($k[$v]=1)&&$u[]=$v);$v=next($a));return$u;};
var_dump($unique($array)); # array(1,4,2,6,9,7)
First was reading that you don't want to use array_unique or similar functions (array_intersect etc.), so this was just a start, maybe it's still of som use:
You can use array_flip PHP Manual in combination with array_keys PHP Manual for your array of integers (Demo):
$array = array (1,4,2,1,6,4,9,7,2,9);
$array = array_keys(array_flip($array));
var_dump($array); # array(1,4,2,6,9,7)
As keys can only exist once in a PHP array and array_flip retains the order, you will get your result. As those are build in functions it's pretty fast and there is not much to iterate over to get the job done.
<?php
$inputArray = array(1, 4, 2, 1, 6, 4, 9, 7, 2, 9);
$outputArray = array();
foreach ($inputArray as $val){
if(!in_array($val,$outputArray)){
$outputArray[] = $val;
}
}
print_r($outputArray);
You could use an intermediate array into which you add each item in turn. prior to adding the item you could check if it already exists by looping through the new array.

str_replace() and strpos() for arrays?

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

Categories