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);
Related
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);
This question already has answers here:
How does PHP 'foreach' actually work?
(7 answers)
Closed 8 years ago.
Consider the code below:
<?php
$arr = array();
$arr['b'] = 'book';
foreach($arr as $key=>$val) {
print "key=>$key\n";
if(!isset($arr['a']))
$arr['a'] = 'apple';
}
?>
It is not displaying 'a'. How foreach works with hash-table(array), to traverse each element. If lists are implement why can't I add more at run time ?
Please don't tell me that I could do this task with numeric based index with help of counting.
Foreach copies structure of array before looping(read more), so you cannot change structure of array and wait for new elements inside loop. You could use while instead of foreach.
$arr = array();
$arr['b'] = 'book';
reset($arr);
while ($val = current($arr))
{
print "key=".key($arr).PHP_EOL;
if (!isset($arr['a']))
$arr['a'] = 'apple';
next($arr);
}
Or use ArrayIterator with foreach, because ArrayIterator is not an array.
$arr = array();
$arr['b'] = 'book';
$array_iterator = new ArrayIterator($arr);
foreach($array_iterator as $key=>$val) {
print "key=>$key\n";
if(!isset($array_iterator['a']))
$array_iterator['a'] = 'apple';
}
I think you need to store array element continue sly
Try
<?php
$arr = array();
$arr['b'] = 'book';
foreach($arr as $key=>$val) {
print "key=>$key\n";
if(!isset($arr['a']))
$arr['a'][] = 'apple';
}
print_r($arr);
?>
In order to be able to directly modify array elements within the loop precede $value with &. In that case the value will be assigned by reference.
http://cz2.php.net/manual/en/control-structures.foreach.php
Try this:
You will get values.
<?php
$arr = array();
$arr['b'] = 'book';
foreach($arr as $key=>$val) {
print "key=>$key\n";
if(!isset($arr['a']))
$arr['a'] = 'apple';
}
echo '<pre>';
print_r($arr);
?>
Output:
key=>b
<pre>Array
(
[b] => book
[a] => apple
)
If you want to check key exist or not in array use array_key_exists function
Eg:
<?php
$arr = array();
$arr['b'] = 'book';
print_r($arr); // prints Array ( [b] => book )
if(!array_key_exists("a",$arr))
$arr['a'] = 'apple';
print_r($arr); // prints Array ( [b] => book [a] => apple )
?>
If you want to use isset condition try like this:
$arr = array();
$arr['b'] = 'book';
$flag = 0;
foreach($arr as $key=>$val) {
print "key=>$key\n";
if(!isset($arr["a"]))
{
$flag = 1;
}
}
if(flag)
{
$arr['a'] = 'apple';
}
print_r($arr);
How about using for and realtime array_keys()?
<?php
$arr = array();
$arr['b'] = 'book';
for ($x=0;$x<count($arr); $x++) {
$keys = array_keys($arr);
$key = $keys[$x];
print "key=>$key\n";
if(!isset($arr['a']))
$arr['a'] = 'apple';
}
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
)
I want to add data to an array dynamically. How can I do that? Example
$arr1 = [
'aaa',
'bbb',
'ccc',
];
// How can I now add another value?
$arr2 = [
'A' => 'aaa',
'B' => 'bbb',
'C' => 'ccc',
];
// How can I now add a D?
There are quite a few ways to work with dynamic arrays in PHP.
Initialise an array:
$array = array();
Add to an array:
$array[] = "item"; // for your $arr1
$array[$key] = "item"; // for your $arr2
array_push($array, "item", "another item");
Remove from an array:
$item = array_pop($array);
$item = array_shift($array);
unset($array[$key]);
There are plenty more ways, these are just some examples.
$array[] = 'Hi';
pushes on top of the array.
$array['Hi'] = 'FooBar';
sets a specific index.
Let's say you have defined an empty array:
$myArr = array();
If you want to simply add an element, e.g. 'New Element to Array', write
$myArr[] = 'New Element to Array';
if you are calling the data from the database, below code will work fine
$sql = "SELECT $element FROM $table";
$query = mysql_query($sql);
if(mysql_num_rows($query) > 0)//if it finds any row
{
while($result = mysql_fetch_object($query))
{
//adding data to the array
$myArr[] = $result->$element;
}
}
You should use method array_push to add value or array to array exists
$stack = array("orange", "banana");
array_push($stack, "apple", "raspberry");
print_r($stack);
/** GENERATED OUTPUT
Array
(
[0] => orange
[1] => banana
[2] => apple
[3] => raspberry
)
*/
Like this?:
$array[] = 'newItem';
In additon to directly accessing the array, there is also
array_push — Push one or more elements onto the end of array
$dynamicarray = array();
for($i=0;$i<10;$i++)
{
$dynamicarray[$i]=$i;
}
Adding array elements dynamically to an Array And adding new element
to an Array
$samplearr=array();
$count = 0;
foreach ($rslt as $row) {
$arr['feeds'][$count]['feed_id'] = $row->feed_id;
$arr['feeds'][$count]['feed_title'] = $row->feed_title;
$arr['feeds'][$count]['feed_url'] = $row->feed_url;
$arr['feeds'][$count]['cat_name'] = $this->get_catlist_details($row->feed_id);
foreach ($newelt as $cat) {
array_push($samplearr, $cat);
}
++$count;
}
$arr['categories'] = array_unique($samplearr); //,SORT_STRING
$response = array("status"=>"success","response"=>"Categories exists","result"=>$arr);
just for fun...
$array_a = array('0'=>'foo', '1'=>'bar');
$array_b = array('foo'=>'0', 'bar'=>'1');
$array_c = array_merge($array_a,$array_b);
$i = 0; $j = 0;
foreach ($array_c as $key => $value) {
if (is_numeric($key)) {$array_d[$i] = $value; $i++;}
if (is_numeric($value)) {$array_e[$j] = $key; $j++;}
}
print_r($array_d);
print_r($array_e);
Fastest way I think
$newArray = array();
for($count == 0;$row = mysql_fetch_assoc($getResults);$count++)
{
foreach($row as $key => $value)
{
$newArray[$count]{$key} = $row[$key];
}
}
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
// )