i need to define the array values as need. Here i say that the value will be 0 to 2. But i need someway to say the value can be null and also it can be 0 to 1000.
$apartment = array(
0,
1,
2
);
foreach ($apartment AS $apt) {
$userApt = $area->getApartments()->get($apt)->getApartment();
echo $userApt . "<br>";
}
Please note that the value can be 0 and it should stop where there is no available value ...
i mean if get(0) is available it should get the value, if get(1) is not available it should stop there and do nothing , so the main purpose is to get the value where it is available, when it is not available, do nothing...
According to your lasts edits, there is no need to build such an array. You can get your objects directly within the loop.
<?php
for($i = 0; $i <= 1000; ++$i) {
$userApt = $area->getApartments()->get($i);
if(!$userApt) {
break;
} else {
var_dump($userApt->getApartment());
}
}
This would stop as soon as an object cannot be retrieved.
Related
I have the following code, which checks is an element exists, and if it exists, it checks for the same name, with an incremented number at the end.
For example, it checks is the key "test" exists in the array $this->elements, and if it exists, it checks for "test2", and so on, until the key doesn't exist.
My original code is:
if (isset($this->elements[$desired])) {
$inc = 0;
do {
$inc++;
$new_desired = $desired . $inc;
} while (isset($this->elements[$new_desired]));
$desired = $new_desired;
}
I tried with:
if (isset($this->elements[$desired])) {
return $this->generateUniqueElement($desired, $postfix);
}
private function generateUniqueElement($desired, $postfix) {
$new_desired = $desired . $postfix;
return isset($this->elements[$new_desired]) ? $this->generateUniqueElement($desired, ++$postfix) : $new_desired;
}
But in my tests there's no speed improvement.
Any idea how can I improve the code? On all the pages, this code is called over 10 000 times. And sometimes even over 100k times.
Anticipated thanks!
Without further knowledge on how you generate this list, here's an idea:
$highestElementIds = [];
foreach($this->elements as $element) {
preg_match('/(.*?)(\d+)/', $element, $matches);
$text = $matches[1];
$id = (int)$matches[2];
if(!isset($highestElementIds[$text])) {
$highestElementIds[$text] = $id;
} else {
if($id > $highestElementIds[$text]) {
$highestElementIds[$text] = $id;
}
}
}
// find some element by a simple array access
$highestElementIds['test']; // will return 2 in your example
If your code is really being called 100k times, it should be a lot faster to iterate your list only once and then get the highest id directly from an array which contains the highest number (since you don't need to iterate through it again).
That being said, I still wonder what's the actual reason for having such a huge array in the first place...
Typical unique IDs are either random (UUID or random chars) or sequential numbers. The latter is as simple as it gets and it can be generated with a simple counter:
function generateNewElement($postfix) {
static $i = 0;
return sprintf('%d%s', $i++, $postfix);
}
echo generateNewElement('foo'), PHP_EOL;
echo generateNewElement('foo'), PHP_EOL;
echo generateNewElement('foo'), PHP_EOL;
echo generateNewElement('foo'), PHP_EOL;
0foo
1foo
2foo
3foo
Of course this is just a generic solution so it may not fit your specific use case.
I have a button next to all my 'shop items' that can remove one of the shop item, however i need it to just remove one, and not rid the entire array of the number, i thought this was possible by using a break statement when i found the number i want to remove, but it removes all of the numbers.
if (isset($_GET['remove']) && isset($_SESSION['shopitems'])) {
if (in_array($_GET['remove'], $_SESSION['shopitems'])) {
for ($i = 0; $i < sizeof($_SESSION['shopitems']); $i++) {
if ($_SESSION['shopitems'][$i] == $_GET['remove']) {
$shopArray = $_SESSION['shopitems'];
if(sizeof($shopArray) == 1) {
$_SESSION['shopitems'] = null;
$_SESSION['added'] = null;
} else {
array_splice($shopArray, $i, $i);
$_SESSION['shopitems'] = $shopArray;
}
break;
}
}
}
}
Here i check if the URL contains the remove variable and the session is set, once i have done this, i check if the array contains the number that is put in the URL, if so i'll start a for loop and check if the key index of the session shop items is equal to the URL variable, if so i want to remove it, however if i use array_splice, suddenly they are all gone, is this because of the function i am using? Or is the break not executing correctly?
Why don't you try array_search() and unset()? It's easier, have a look at the code below and adapt it to your situation:
$array = [1, 5, 6, 12];
$wantToRemove = 5;
$key = array_search($wantToRemove, $array);
unset($array[$key]);
var_dump($array);
You can format your $_SESSION['shopitems'] like this :
$_SESSION['shopitems'] = array (
"item_id" => "item_info",
"item2_id" => "item2_info",
...
)
and do unset($_SESSION['shopitems'][$_GET['remove']]).
Your code could be :
if (isset($_GET['remove']) && isset($_SESSION['shopitems']))
if (isset($_SESSION['shopitems'][$_GET['remove']]))
unset($_SESSION['shopitems'][$_GET['remove']])
How do I delete the whole line from an array? When the delete-button is pressed it should delete the whole line.
my array looks like that:
$liste[0][0] = email-user1
$liste[0][1]= password-user1
$liste[1][0] = email-user2
$liste[1][1]= password-user2
So if I delete the user one, the user2 should just take the place from user1(which should just disappear).
if (isset($_GET['delete'])){
$id=key($_GET['delete']);
for ($i = 0; $i < count($liste); $i++){
if ("$i"=="$id"){
unset($liste[$id][0]);
unset($liste[$id][1]);
unset($liste[$id][2]);
}
else{
}
}
update
I'm using array_splice($liste, $id, 1); now but everytime I try to save it to the file I get an error: implode(): Invalid arguments passed. For saving it to the file, I use the following function:
function saveDataToFile($fileName, $liste){
$file=fopen($fileName,"w");
for ($i = 0; $i < count($liste); $i++) {
$zArray=$liste[$i];
$zeile=implode("|", $zArray);
if(strlen($zeile) > 0){
$zeile=$zeile."\r\n";
fwrite($file, $zeile);
}
}
fclose($datei);
}
Try the below code:
$liste[0][0] = "email-user1";
$liste[0][1]= "password-user1";
$liste[1][0] = "email-user2";
$liste[1][1]= "password-user2";
$liste[2][0] = "email-user3";
$liste[2][1]= "password-user3";
unset($liste[1]); // say you want to delete this row
$new_arr = $liste;
unset($liste);
$i=0;
foreach($new_arr as $value){
$liste[$i] = $value;
$i++;
}
You can use array_splice() method:
array_splice($liste, $id, 1);
$liste[0][0], $liste[0][1] and $liste[0][2] are in real nothing else than a value array(value, value, value) (the inner array) which is assigned to $liste[0] (the outer array)
unsetting this (outer) array value $liste[0] is enough:
unset($liste[$id]);
If you care about the keys of this array (I see you loop from 0..n), you need to reindex your array using:
$liste = array_values($liste);
This will make your array behaving more like arrays normally do in other programming languages
Good practice is to use foreach instead of for. In this case you don't need to reindex:
for ($liste as $key=>$value){
if ("$key"=="$id"){
unset($liste[$key]);
}
But anyway you don't have to loop through an array just for finding a key. It's enough doing this:
if (isset($liste[$id])) { /* optional: check if the key exists */ }
unset($liste[$id]);
Im using wordpress as my base and I need to output the post meta for all my posts, but only for a certain number of keys.
What I intend to do is to save a list of all my keys, that im going to use to query wordpress for metadata for that post.
Below is my code.
//HERE YOU CAN SEE THE KEYS IMM USING ATM
$nyckellista[] = array("ebutik_allm_bas_operativsystem" ,"--foretagsform"
,"ebutik_allm_bas_omsättning");
$i = 0;
//Here im trying to query the get_post_meta with my keys and save the result (it's an array aof values that it return)
foreach($nyckellista as $nyckel)
{
$nyckellista[$i] = get_post_meta($post->ID,$nyckel,false);
echo $i . "Nyckel:" . $nyckel[$i];
$i++;
}
//HERE ME TRYING TO PRINT THE ARRAY CONTENTS
$count = count ($nyckellista);
echo $count;
for($y=1; $y <= $count; $y++)
{
$countmore=count($nyckellista[$y]);
for($x=1; $x <= $countmore; $x++)
{
print ($nyckellista[$y][$x] . "<br> ");
}
echo "<br>";
}
WHAT AM I DOING WRONG?
In the first line the $nyckellista variable is being declared implicitly as an array and then you're assigning to its first position an array of values.
Is this what you need/intend?
Edit:
Another point is, in the counts area of the code, that php arrays get numeric indexes starting at 0, not at 1 (see Example #4 in PHP array reference)
I am theming a drupal content type, and I have a set of similarly named variables. e.g. field_anp_1, field_anp_2,..., field_anp_10. I want to dynamically print them out from within a for loop. Normally, one would print the values out individually by doing something like:
print $field_anp_1[0]['value'];
in my case, I can't do this because the last number changes. So, within a for loop, how would one print out these fields? I tried variable variables, but I don't seem to understand exactly what is going on there - and I don't think it likes the fact that this in an array. Any help would be greatly appreciated!
Definitely not an array. But you can use a variable as the name of a variable with {..}
ghoti#pc:~ $ cat invar.php
#!/usr/local/bin/php
<?php
$field_anp_3="three";
$field_anp_2="two";
for ($i=1; $i<5; $i++) {
$thisvar="field_anp_" . $i;
if (isset(${$thisvar})) {
printf("%s: %s\n", $i, ${$thisvar});
} else {
printf("%s: not set\n", $i);
}
}
ghoti#pc:~ $ ./invar.php
1: not set
2: two
3: three
4: not set
Alternately, if you are sure that the variables that do exist will be sequential. you can stop on failure (per comments below):
#!/usr/local/bin/php
<?php
$field_anp_1="one";
$field_anp_2="two";
$field_anp_3="three";
for ($i=1; $i<5; $i++) {
$thisvar="field_anp_" . $i;
if (!isset(${$thisvar})) {
break;
}
printf("%s: %s\n", $i, ${$thisvar});
}
I can see no reason for having an untold number of variables generated like that. But this is how you could collect them:
$vars = array();
foreach(get_defined_vars() as $name => $value) {
if(strpos($name, 'field_anp_') === 0) {
$vars[$name] = $value;
}
}
Now you would have your values as an associative array in $vars. Instead of adding the values to $vars, you could print them directly.
Update In response to your comment
$array = array('foo' => 'bar');
$x = 'foo';
$field_anp_bar = 'baz';
echo ${'field_anp_' . $array[$x]};
Ok, I figured it out. I simply needed to be more specific with PHP. To call a variable such as: $field_anp_0[0]['value'] from within a for loop, where 0 is increasing, one simply needs to do the following:
<?php
$numbers = array(123,235,12332,2342);
for($i; $i<count($numbers); $i++){
$var = "field_anp_".$numbers[$i];
printf("%s\n", ${$var}[0]['value']);
}
?>
This will allow me to list the fields that I will need to have printed out in the order I need to have them printed out. Then, I can use a for loop to print out a themed table for instance.
Thank you for the help!