How to store things in a set in PHP? - php

How do I write code such that I can put things in a set and only the unique entries are kept?
for($i=0;$i<$count;$i++) {
$variable->put($some_object)
}

SplObjectStorage
$s = new SplObjectStorage();
$s->attach($some_object);
$s->attach($some_other_object);
Note that you can also use arrays, the keys are unique and reassigning a new value to existing key overwrites the new one. But with arrays you have come up with your own ID-s, with SplObjectStorage you don't.
Array example
$a = array();
$a['key1'] = $some_object;
$a['key1'] = $some_other_object;
In the above example only 'key1' is kept.

Related

Store array add handle to variable

Hey in a recent project I got this working and was quite amazed that such a snipped works.
$parentRef = &$elements[$targetPath]->
{$contentTypeMap[$contentTypeIdMap[$contentTypeId]]};
if(is_array($parentRef)) {
$parentRef = &$parentRef[];
}
$parentRef = $element;
It was quite intuitive that it might work that way but what exactly is
$parentRef[] returning to make this work?
If I var_dump it, i get null.
Here is a simplified example which seems to work.
<?php
$arr = [1, 2];
$ref = &$arr[];
$ref = 3;
foreach($arr as $n) {
echo $n;
}
This example returns 123 just to verify that it works.
In your example $arr[] will create new element in array with NULL value. The ampersand is reference to this position, so when you store something to $ref, it will be stored in this new position, because $ref is just reference (something like pointer, but its not pointer!) to this new element in array

$array["key"] = value; or array_merge(), which is the fastest way?

Which is the best (performance efficiency) way to create an array in multiple files?
This:
$arr = array();
$arr["key1"] = "val1";
$arr["key2"] = "val2";
include "arr_2.php";
arr_2.php:
$arr["key3"] = "val3";
$arr["key4"] = "val4";
Or this:
$arr = array("key1"=>"val1", "key2"=>"val2");
include "arr_2.php";
arr_2.php:
$arr = array_merge($arr, array("key3"=>"val3", "key4"=>"val4"));
ARRAY KEY => VALUE is faster than ARRAY_MERGE.
KEY VALUE is a simple creation of ARRAY ELEMENTS similar to creating a simple variable and assigning a value to it.
ARRAY_MERGE will always take previous array and merge values all over again, which involves more processing.
You will notice significant performance impact when run in a loop.
Hope this helps!

array_merge all except for one key/value pair? PHP

I'd like to merge two user objects (one is a duplicate). The problem is, one user object has some fields the other doesn't and vice versa. I'd like to array_merge all the key/value pairs except for the id. Is there anyway to do this?
Here is my code below. When I try to merge, the $second_user doesn't delete like I would like it to. If I comment out the merge block, it deletes duplicates properly without merging. However, when I comment it back in, there are still duplicates.
I think the issue is trying to use array_merge when id is an immutable field.
public function combine($first_user, $second_user)
{
// Always make sure $first_user is the "original" user that we're going merge.
if ($first_user->created_at > $second_user->created_at) {
$tmp = $second_user;
$second_user = $first_user;
$first_user = $tmp;
}
// Merge their data and save to the first user
$updated_user = array_merge(array_filter($second_user->toArray()), array_filter($first_user->toArray()));
$first_user->fill($updated_user)->save();
$second_user->delete();
}
Just unset the id after the merge:
$array = array_merge($arr1, $arr2);
unset($array['id']);
I'm not 100% sure if I understood correctly, but if you wan't to achieve the following:
use $first_user var as the "main" var for storing data
and preserve $first_user var data (including ID)
and add fields of $second_user to the $first_user while preserving existing $first_user data
If thats the case, instead of array_merge just use array + operator:
$arr1 = array_filter($first_user->toArray());
$arr2 = array_filter($second_user->toArray());
$updated_user = $arr1 + $arr2; // union
The + operator returns the right-hand array appended to the left-hand array; for keys that exist in both arrays, the elements from the left-hand array will be used, and the matching elements from the right-hand array will be ignored.

Creating an array in PHP

If I wanted to create an array in PHP with the following format, what would be the best way to approach it? Basically I want to declare the array beforehand, and then be able to add the values to person_id, name and age.
'person_id' => array('name'=>'jonah', 'age'=> 35)
To the first answer #Joe, first of all, your class doesn't support encapsulation since your attributes are public. Also, for someone who doesn't know how to create an array, this concept may be a bit complicated.
For the answer, changing a bit the class provided by #Joe, PHP provide a simple way of using arrays:
If you need many rows for this array, each row has a number, if not, remove the [0] for only one entry.
$persons = array();
$persons[0]['person_id'] = 1;
$persons[0]['name'] = 'John';
$persons[0]['age'] = '27';
Depending on how you want to use it, you could make a simple object:
class Person
{
public $person_id;
public $name;
public $age;
}
$person = new Person; // make the object beforehand
$person->person_id = 123; // their id
$person->name = 'Joe'; // my name
$person->age = 21; // yeah, right
This is virtually identical to an array (in terms of how it's used) except for:
Instead of new array() you use new Person (no brackets)
Instead of accessing items with ['item'] you use ->item
You can start with an empty array:
$arr = Array();
Then add stuff to that array:
$arr['person_id'] = Array();
$arr['person_id']['name'] = "jonah";
$arr['person_id']['age'] = 35;

change last key name from array in php

i want to be able to change the last key from array
i try with this function i made:
function getlastimage($newkey){
$arr = $_SESSION['files'];
$oldkey = array_pop(array_keys($arr));
$arr[$newkey] = $arr[$oldkey];
unset($arr[$oldkey]);
$_SESSION['files'] = $arr;
$results = end($arr);
print_r($arr);
}
if i call the function getlastimage('newkey') it change the key!but after if i print the $_SESSION the key is not changed? why this?
When you set $arr = $_SESSION['files'], you are actually making a copy of $_SESSION['files']. Everything you do to $arr is not done to the original.
Try this:
$arr =& $_SESSION['files'];
Note the ampersand after the equals sign. That will make $arr a reference to $_SESSION['files'], and your updates to $arr will affect $_SESSION['files'] as well, since they both reference the same content.
The other solution is of course to just copy the array back by putting $_SESSION['files'] = $arr; at the end of your function.
Wow, your code is a mess!
1) You're setting $_SESSION in a new array. In order for your changes to take affect, you'll need to set back to your original $_SESSION array, otherwise your new array will just be forgotten.
2) It would be easier to simply array_pop() to get the last element and set it to the new key, rather than wasting the time to fetch all the keys and pop the last key off, then fetch the value from the array again. The old key value is worthless.
try update the session
$_SESSION['files'] = $arr;

Categories