Lets say that we have dynamically generated array.
$arr[1]["a"] = "value";
$arr[1]["b"] = "value";
$arr[1]["c"] = "value";
$arr[2]["a"] = "value";
$arr[2]["b"] = "value";
$arr[2]["c"] = "value";
$arr[2]["d"] = "value";
$arr[3]["a"] = "value";
$arr[3]["g"] = "value";
Generating the Array can be manipulated, so do not take this example like a core lines.
As you see there is different keys, but at the end we must get:
$arr[1]['a'] = 'value';
$arr[1]['b'] = 'value';
$arr[1]['c'] = 'value';
$arr[1]['d'] = 'empty value';
$arr[1]['g'] = 'empty value';
$arr[2]['a'] = 'value';
$arr[2]['b'] = 'value';
$arr[2]['c'] = 'value';
$arr[2]['d'] = 'value';
$arr[2]['g'] = 'empty value';
$arr[3]['a'] = 'value';
$arr[3]['b'] = 'empty value';
$arr[3]['c'] = 'empty value';
$arr[3]['d'] = 'empty value';
$arr[3]['g'] = 'value';
non empty values are different, so array_merge is not so using good idea.
I think you want this (this is horribly inefficient but my brain is struggling)
$keys = array();
foreach($arr as $array){
$keys = array_merge($keys, array_keys($array));
}
//$keys now has all unique keys
foreach($arr as $array){
foreach($keys as $key){
if(!isset($array[$key])){$array[$key] = null}
}
}
This is untested but i think it should work
I Guess is you want to fill your array with default values ... you can use array_fill to do that
$keys = array("a","b","c","d","g");
$arr[1] = array_combine($keys,array_fill(0, 5, 'empty value'));
$arr[1]["a"] = "value";
$arr[1]["b"] = "value";
$arr[1]["c"] = "value";
print_r($arr[1]);
Output
Array
(
[a] => value
[b] => value
[c] => value
[d] => empty value
[g] => empty value
)
Related
I build an array like this:
$array = array(); // start with empty one
$array[] = 'foobar';
$array[] = 'hello';
$array[] = 'foobar';
$array[] = 'world';
$array[] = 'foobar';
As you can see, foobar is repeated three times. How do I make it so that the array skips the key if it was already added previously? So in this case, the second and third foobar should not be added.
<?php
$array = array(); // start with empty one
$array[] = 'foobar';
$array[] = 'hello';
$array[] = 'foobar';
$array[] = 'world';
$array[] = 'foobar';
$array = array_unique($array); // removes all the duplicates
var_dump( $array );
?>
From PHP Manual
This approach is used if you want to "SKIP" items. Demo
$array = array("hello", "world", "foobar");
$value1 = "foobar";
$value2 = "test";
if(!in_array($value1, $array)) $array[] = $value1; // this will not be added because foobar already exists in the array
if(!in_array($value2, $array)) $array[] = $value2; // this will be added because it does not exist in the array
If you don't necessarily have to skip the items and just want the output, you can use array_unique like so: Demo
$array = array("hello", "world", "foobar", "foobar");
$array = array_unique($array);
I write a code for sync two array and know which was must delete and which was add to new array.
<?php
$currentArray = array('ali', 'hasan', 'husein'); //base array read from database
$saveArray = array('husein', 'Hasan', 'taghi'); //requested item for save/delete in database
$deleteArray = array();
$addArray = array();
$currentArray = array_map('strtolower', $currentArray);
$saveArray = array_map('strtolower', $saveArray);
foreach ($currentArray as $a) {
if (!in_array($a, $saveArray))
$deleteArray[] = $a;
}
foreach ($saveArray as $a) {
if (!in_array($a, $currentArray))
$addArray[] = $a;
}
echo 'must be deleted:';
var_dump($deleteArray);
echo 'must be added:';
var_dump($addArray);
?>
Output:
must be deleted:
array
0 => string 'ali' (length=3)
must be added:
array
0 => string 'taghi' (length=5)
Now, Do you thinks is it better, faster and simpler code for this action?
You can use array_udiff() for this, using strcasecmp() as the callback function.
$currentArray = array('ali', 'hasan', 'husein');
$saveArray = array('husein', 'Hasan', 'taghi');
$deleteArray = array_udiff($currentArray, $saveArray, 'strcasecmp');
$addArray = array_udiff($saveArray, $currentArray, 'strcasecmp');
See demo
The values must be the same.
$currentArray = array_map('strtolower', $currentArray);
$saveArray = array_map('strtolower', $saveArray);
And basically use use Array diff.
$deleteArray = array_diff($currentArray, $saveArray);
$addArray = array_diff($saveArray, $currentArray);
PHP has a function extract that will convert an array like this:
$array = array(
'var1' => 1,
'var2' => 2
);
to:
$var1 = 1;
$var2 = 2;
now, I need the opposite, i have few variables:
$var3 = 'test';
$test = 'another';
$datax = 1;
that needs to be:
$array = array(
'var3' => 'test',
'test' => 'another',
'datax' => 1
);
Is there something like this in PHP?
You can use compact() to achieve this.
$var3 = 'test';
$test = 'another';
$datax = 1;
$array = compact('var3', 'test', 'datax');
Reference: http://php.net/manual/en/function.compact.php
like this
$preDefined = (get_defined_vars());
$var3 = 'test';
$test = 'another';
$datax = "1";
$newDefined = array_diff(get_defined_vars(), $preDefined);
print_r($newDefined);
$array = get_defined_vars()
See get_defined_vars()
You'd have to be really sure you wanted to do this (it includes things in the global scope automatically) but you can use
$my_vars = get_defined_vars();
If you want it more selective than that, you could look at filtering it like this:
$my_vars = pack_vars(get_defined_vars())
function pack_vars ($defined_vars)
{
$packed = array();
$ignored = array('dont_use_this', 'ignored_var', 'ignore_this_too');
foreach ($defined_vars AS $key => $value)
{
if (!in_array($key, $ignored))
{
$packed[$key] = $value;
}
}
return $packed;
}
I have several arrays: $n, $p, $a
Each array is the same:
$n = array()
$n['minutes'] = a;
$n['dollars'] = b;
$n['units'] = c;
$p = array()
$p['minutes'] = x;
$p['dollars'] = y;
$p['units'] = z;
etc...
I also have a simple array like this:
$status = array('n', 'p', 'a');
Is it possible for me to use the $status array to loop through the other arrays?
Something like:
foreach($status as $key => $value) {
//display the amounts amount here
};
So I would end up with:
a
x
b
y
c
z
Or, do I need to somehow merge all the arrays into one?
Use:
$arrayData=array('minutes','dollars','units');
foreach($arrayData as $data) {
foreach($status as $value) {
var_dump(${$value}[$data]);
}
}
foreach($n as $key => $value) {
foreach($status as $arrayVarName) (
echo $$arrayVarName[$key],PHP_EOL;
}
echo PHP_EOL;
}
Will work as long as all the arrays defined in $status exist, and you have matching keys in $n, $p and $a
Updated to allow for $status
You could use next() in a while loop.
Example: http://ideone.com/NTIuJ
EDIT:
Unlike other answers this method works whether the keys match or not, even is the arrays are lists, not dictionaries.
If I understand your goal correctly, I'd start by putting each array p/n/... in an array:
$status = array();
$status['n'] = array();
$status['n']['minutes'] = a;
$status['n']['dollars'] = b;
$status['n']['units'] = c;
$status['p'] = array();
$status['p']['minutes'] = a;
$status['p']['dollars'] = b;
$status['p']['units'] = c;
Then you can read each array with:
foreach($status as $name => $values){
echo 'Array '.$name.': <br />';
echo 'Minutes: '.$values['minutes'].'<br />';
echo 'Dollars: '.$values['dollars'].'<br />';
echo 'Units: '.$values['units'].'<br />';
}
For more information, try googling Multidimensional Arrays.
I have the following code snippet.
$items['A'] = "Test";
$items['B'] = "Test";
$items['C'] = "Test";
$items['D'] = "Test";
$index = 0;
foreach($items as $key => $value)
{
echo "$index is a $key containing $value\n";
$index++;
}
Expected output:
0 is a A containing Test
1 is a B containing Test
2 is a C containing Test
3 is a D containing Test
Is there a way to leave out the $index variable?
Your $index variable there kind of misleading. That number isn't the index, your "A", "B", "C", "D" keys are. You can still access the data through the numbered index $index[1], but that's really not the point. If you really want to keep the numbered index, I'd almost restructure the data:
$items[] = array("A", "Test");
$items[] = array("B", "Test");
$items[] = array("C", "Test");
$items[] = array("D", "Test");
foreach($items as $key => $value) {
echo $key.' is a '.$value[0].' containing '.$value[1];
}
You can do this:
$items[A] = "Test";
$items[B] = "Test";
$items[C] = "Test";
$items[D] = "Test";
for($i=0;$i<count($items);$i++)
{
list($key,$value) = each($items[$i]);
echo "$i $key contains $value";
}
I haven't done that before, but in theory it should work.
Be careful how you're defining your keys there. While your example works, it might not always:
$myArr = array();
$myArr[A] = "a"; // "A" is assumed.
echo $myArr['A']; // "a" - this is expected.
define ('A', 'aye');
$myArr2 = array();
$myArr2[A] = "a"; // A is a constant
echo $myArr['A']; // error, no key.
print_r($myArr);
// Array
// (
// [aye] => a
// )