Take the last value of the array. PHP: Removing array elements. Removing elements using string methods

key output (24)

I'm writing a SQL query creator using some parameters. In Java, it is very easy to detect the last element of an array from a for loop by simply checking the current position of the array with the length of the array.

For(int i=0; i< arr.length;i++){ boolean isLastElem = i== (arr.length -1) ? true: false; }

In PHP they have non-integer indexes for accessing arrays. So you have to iterate through the array using a foreach loop. This becomes problematic when you need to make some decision (in my case, add an or/and parameter when building the query).

I'm sure there must be some standard way to do this.

How do you solve this in PHP?

Answers

You can also do something like this:

End($elements); $endKey = key($elements); foreach ($elements as $key => $value) ( ​​if ($key == $endKey) // -- this is the last item ( // do something ) // more code )

You can also try this to make your query...shown here using INSERT

"monday","two"=>"tuesday","three"=>"wednesday","four"=>"thursday","five"=>"friday","six"=>"saturday"," seven"=>"sunday"); $keys = array_keys($week); $string = "INSERT INTO my_table (""; $string .= implode("","", $keys); $string .= "") VALUES (""; $string .= implode("","" , $week); $string .= "");"; echo $string; ?>

I have a strong feeling that at the root of this "XY problem" the OP simply wanted an implode() function.

Because your intent to find the EOF array is just glue. Check out the tactics below. You don't need EOF:

$given_array = array("column1"=>"value1", "column2"=>"value2", "column3"=>"value3"); $glue = ""; foreach($given_array as $column_name=>$value)( $where .= " $glue $column_name = $value"; //appending the glue $glue = "AND"; ) echo $where;

Column1 = value1 AND column2 = value2 AND column3 = value3

Here's another way to do it:

$arr = range(1, 10); $end = end($arr); reset($arr); while(list($k, $v) = each($arr)) ( if($n == $end) ( echo "last!"; ) else ( echo sprintf("%s ", $v); ) )

For scenarios generating SQL queries or anything that does another action on the first or last element, it is much faster (almost twice as fast) to avoid using unnecessary variable checks.

The current accepted solution uses a loop and a check inside the loop that will be done every_single_iteration, the correct (fast) way to do this is:

$numItems = count($arr); $i=0; $firstitem=$arr; $i++; while($i<$numItems-1){ $some_item=$arr[$i]; $i++; } $last_item=$arr[$i]; $i++;

A small home test showed the following:

test1: 100,000 runs of the morgue model

time: 1869.3430423737 milliseconds

test2: 100,000 runs of the model, if the latest

time: 3235.6359958649 milliseconds

I like the following as I feel it's pretty neat. Let's say we create a string with delimiters between all elements: for example, a, b, c

$first = true; foreach ($items as $item) ( $str = ($first)?$first=false:", ".$item; )

$page_comment): ?>

When toEnd reaches 0, it means it is on the last iteration of the loop.

$toEnd = count($arr); foreach($arr as $key=>$value) ( ​​if (0 === --$toEnd) ( echo "last index! $value"; ) )

The last value is still available after the loop, so if you just want to use it for more stuff after the loop, this is better:

Foreach($arr as $key=>$value) ( ​​//something ) echo "last index! $key => $value";

If you don't want to treat the last value as special inner loops. This should be faster if you have large arrays. (If you are reusing an array after a loop within the same scope, you need to "copy" the array first).

//If you use this in a large global code without namespaces or functions then you can copy the array like this: //$array = $originalArrayName; //uncomment to copy an array you may use after this loop //end($array); $lastKey = key($array); //uncomment if you use the keys $lastValue = array_pop($array); //do something special with the last value here before you process all the others? echo "Last is $lastValue", "\n"; foreach ($array as $key => $value) ( ​​//do something with all values ​​before the last value echo "All except last value: $value", "\n"; ) //do something special with the last value here after you process all the others? echo "Last is $lastValue", "\n";

And to answer your original question "in my case, add the or/and parameter when building the query"; this will cover all the values ​​and then concatenate them into a string with "and" between them, but not before the first value or after the last value:

$params = ; foreach ($array as $value) ( ​​$params = doSomething($value); ) $parameters = implode(" and ", $params);

You can still use this method with associative arrays:

$keys = array_keys($array); for ($i = 0, $l = count($array); $i< $l; ++$i) { $key = $array[$i]; $value = $array[$key]; $isLastItem = ($i == ($l - 1)); // do stuff } // or this way... $i = 0; $l = count($array); foreach ($array as $key =>$value) ( ​​$isLastItem = ($i == ($l - 1)); // do stuff ++$i; )

Another way is to remember the previous result of the loop and use it as the final result:

$result = $where = ""; foreach ($conditions as $col => $val) ( $result = $where .= $this->getAdapter()->quoteInto($col." = ?", $val); $where .= " AND " ; ) return $this->delete($result);

I personally use a design like this which makes it easy to use html elements

    And
  • : Just change the equality for another property...

    An array cannot contain false elements, but all other elements are passed to a false boolean value.

    $table = array("a" , "b", "c"); $it = reset($table); while($it !== false) ( echo "all loops";echo $it; $nextIt = next($table); if ($nextIt === false || $nextIt === $it) ( echo " last loop or two identical items"; ) $it = $nextIt; )

    You can dirctly get the latest index:

    $numItems = count($arr);

    echo $arr[$numItems-1];

    Assuming you have an array stored in a variable...

    Foreach($array as $key=>$value) ( ​​echo $value; if($key != count($array)-1) ( echo ", "; ) )

    It looks like you want something like this:

    $array = array("First", "Second", "Third", "Last"); foreach($array as $key => $value) ( ​​if(end($array) === $value) ( ​​echo "last index!" . $value; ) )

    If you need to do something for every element except the first or last, and only if there is more than one element in the array, I prefer the following solution.

    I know there are many solutions above and posted months/year before mine, but this is what I feel is quite elegant. Checking each loop is also a logical check, as opposed to a numeric check "i = (count-1)", which can reduce overhead.

    The loop structure may seem awkward, but you can compare it to the ordering of (start), tfoot (end), tbody (current) tags in an HTML table.

    $first = true; foreach($array as $key => $value) ( ​​if ($first) ( $first = false; // Do what you want to do before the first element echo "List of key, value pairs:\n"; ) else ( // Do what you want to do at the end of every element // except the last, assuming the list has more than one element echo "\n"; ) // Do what you want to do for the current element echo $key . " => " . $value; )

    For example, in web development terms, if you want to add border-bottom for every element except the last one in an unordered list (ul) then you can add instead border-top for every element except the first(CSS:first-child, supported by IE7+ and Firefox/Webkit, supports this logic, whereas:last-child is not supported by IE7).

    You can freely reuse the $first variable for each nested loop and everything will work fine since each loop makes $first false during the first process of the first iteration (so breaks/exceptions won't cause problems).

    $first = true; foreach($array as $key => $subArray) ( if ($first) ( $string = "List of key => value array pairs:\n"; $first = false; ) else ( echo "\n"; ) $string .= $key . "=>("; $first = true; foreach($subArray as $key => $value) ( ​​if ($first) ( $first = false; ) else ( $string .= ", "; ) $string .= $key . "=>" . $value; ) $string .= ")"; ) echo $string;

    Example output:

    List of key => value array pairs: key1=>(v1_key1=>v1_val1, v1_key2=>v1_val2) key2=>(v2_key1=>v2_val1, v2_key2=>v2_val2, v2_key3=>v2_val3) key3=>(v3_key1=>v3_val1 )

    One way could be to detect the next iterator. If there is no next on the iterator, it means you are in the last loop.

    Foreach ($some_array as $element) ( if(!next($some_array)) ( // This is the last $element ) )

    So, if your array has unique array values, then determining the last iteration is trivial:

    Foreach($array as $element) ( if ($element === end($array)) echo "LAST ELEMENT!"; )

    As you can see, this works if the last element appears only once in the array, otherwise you will get a false alarm. In this one, no, you need to compare the keys (which are of course unique).

    Foreach($array as $key => $element) ( end($array); if ($key === key($array)) echo "LAST ELEMENT!"; )

    Also note the strict contact operator, which is quite important in this case.

    Here's my solution: just get the counter of your array, minus 1 (starting from 0).

    $lastkey = count($array) - 1; foreach($array as $k=>$a)( if($k==$lastkey)( /*do something*/ ) )

    It looks like you want something like this:

    $numItems = count($arr); $i = 0; foreach($arr as $key=>$value) ( ​​if(++$i === $numItems) ( echo "last index!"; ) )

    That being said, you don't want to - iterate over an "array" using foreach in php.

    There are already many answers, but it's also worth looking into iterators, especially since it was asked for the standard way:

    $arr = range(1, 3); $it = new CachingIterator(new ArrayIterator($arr)); foreach($it as $key => $value) ( ​​if (!$it->hasNext()) echo "Last:"; echo $value, "\n"; )

    You may find something that makes it more flexible for other cases as well.

    Fatal error: Calling a member function... on a non-object

    Happens with code similar to xyz->method() where xyz is not an object and therefore this method cannot be called.

    This is a fatal error that will stop the script (forward compatibility notice: this will become a catching bug starting with PHP 7).

    Most often, this is a sign that the code lacks error checking. Confirm that an object is in fact an object before calling its methods.

    a typical example would be

    // ... some code using PDO $statement = $pdo->prepare("invalid query", ...); $statement->execute(...);

    In the example above, the request cannot be prepared and prepare() assigns false to $statement . Trying to call the execute() method will result in a Fatal Error because false is a "non-object" because the value is a boolean.

    Find out Why your function returned a boolean value instead of an object. For example, check the $pdo object for the last error that occurred. The details of how to debug this will depend on how errors are handled for the particular function/object/class.

    Even if ->prepare fails, your database handle $pdo does not fall into the current scope. Find where he decided. Then pass it as a parameter, store it as a property, or share it through the global scope.

    Another problem could be conditionally creating an object and then trying to call a method outside of that conditional block. For example

    If ($someCondition) ( $myObj = new MyObj(); ) // ... $myObj->someMethod();

    By trying to execute a method outside of a conditional block, your object cannot be defined.

    Related questions:

    • Calling a member function on a non-object
    • List of all PHP "Fatal error: Call to member function... on non-object" Questions

    PHP is promising and modern: high-quality syntax and the ability to do semantics beyond what is permitted. The implementation of object-oriented programming ideas and the freedom to change the type of a variable makes your wildest fantasies come true.

    Arrays are an ancient design, and associative ones are more a tribute to the times than a requirement of practice. Although there are a sufficient number of tasks that involve the creation of collections of data of non-predetermined content (quantity, values, types and indexes), which are available for viewing and use in loops. The last element of the array is available using any creation method. Arrays - regular and associative - allow you to create lists, but in normal PHP syntax this has limited use.

    Current array value

    If we abstract from indexes and use the construction

    $arData = new scField(); // scNumber, scString, scParagraph, ...

    where scField() is the constructor of an abstract object - an “information element” that has descendants: numbers (scNumber), strings (scString), phrases (scParagraph), ... we get in PHP: the last element = an array of objects that exhibits its properties as actual element.

    Essentially, it doesn't matter which element is considered relevant, but in this case you will have to keep track of the pointer (in PHP - a cursor) inside the array. More often, you need to have your own element pointer. There is no need for a cursor in PHP's "last element = array" idea. Accessible through the end() and array_pop() functions, the last element delegates its properties to the array. Using array_pop() in addition automatically pops the array to the previous element and its properties change accordingly. This makes it possible to move through the elements.

    So, putting PHP syntax in context, retrieving the last element of an array actually means using its properties. Consistently, by placing and removing elements, we obtain the dynamics of properties, the dynamics of a new one formed within the limits of the available syntax.

    First and other elements

    There are functions for working with the first element of the array and moving the internal pointer. In normal syntax that implements classical programming practice, they are applicable. Regarding the creation of arrays with dynamically changing meaning - no.

    In programming, we are always talking about making decisions: variables take values, conditional statements change the course of the algorithm, loops analyze something, and ultimately a result is produced.

    If you shift the center of gravity to the element itself and let it make its own decisions, the implementation of the program takes on a completely different, meaningful look. Most often, this is the method that allows you to achieve the goal, especially when it comes, for example, to using numerous *.docx document tags written in the Open XML standard.

    In PHP, getting the last element of an array has a new meaning and good possibilities.

    Loading files and dynamics of array properties

    When a site provides the ability to download any files, it is convenient to use the idea of ​​an abstract object, for example, scFile and its descendants scImage, scDocument, scTabe, which will have the same properties, but their manifestation and meaning (content) will be different. In the context of PHP syntax (last element = array), using the end() function, you can use it as the last element defines. This solution is interesting because it inverts the usual representations and allows you to navigate through the data structure as it was formed.

    This use of arrays gives them completely new content. This is provided by the PHP syntax, but using it this way opens up a lot of possibilities.

    Having provided methods for visualization, saving in a database, restoring to working condition (for example), you will not have to think about what to do in a particular case. All downloaded files are placed in the array sequentially, and when it is processed, the same methods are always called according to the same scheme, but the image file will be displayed as is, the spreadsheet file as a table, and the document as the corresponding text. Accessible through PHP syntax, the last element of the array is equipped with its properties and specific content.

    In the latter case, the document always has characters, lines, numbers and, most importantly, formatting. Keeping track of each element is difficult, but by providing the proper object for each format element, you can get the document as is without thinking.

    Stack and recursion within syntax

    When working only with the last element, the main condition is the stack, but when this element is executed and the same construction is used in it, and especially itself, it is recursion. You can say a lot of good things about PHPOffice libraries, for example PHPWord, but it is impossible to say that they implement a full-fledged mechanism that translates the source document formatting into the result.

    Indeed, using PHPOffice\PHPWord you can simply open any Word document (*.docx), but this is just an archive of many structured xml files, pictures, objects, etc.

    At the same time, if you take only xml files, although they are interrelated (in terms of styles, tables, pictures), it will not be possible to create a new document based on the old one and simply transfer the desired changes to it (for example, change the font, colors, formatting). There are many options for using Open XML tags, and even such a well-functioning product as MS Word does not always cope with the user’s ideas, making mistakes.

    Actually, a *.docx file is a zip archive, with a clear and understandable structure. Using a small number of objects, you can formally describe it and obtain, at the time of reading, a full-fledged, independent data structure that can be manipulated semantically.

    In this case, the information in the document is a formal data structure. By giving it dynamics, you can easily move to the level of meaning and abstract from syntax.

    Reg.ru: domains and hosting

    The largest registrar and hosting provider in Russia.

    More than 2 million domain names in service.

    Promotion, domain mail, business solutions.

    More than 700 thousand customers around the world have already made their choice.

    Bootstrap framework: fast adaptive layout

    Step-by-step video course on the basics of adaptive layout in the Bootstrap framework.

    Learn to typesetting simply, quickly and efficiently using a powerful and practical tool.

    Layout to order and get paid.

    *Mouse over to pause scrolling.

    Back forward

    PHP: Removing array elements

    We are faced with a seemingly trivial task: removing an array element. Or several elements.

    However, for all its simplicity, there are options that are not entirely obvious and are worth knowing about if you want to take PHP a little further than "Hello, world!" :)

    Let's start with the base itself: to remove one element, you need to use the function unset():

    Unset($array); unset($array["foo"]);

    Unset($array, $array); unset($array["foo"], $array["bar"]);

    The next logical question is: how to delete multiple elements that follow each other (i.e. adjacent)? To remove multiple adjacent elements, use the function array_splice():

    Array_splice($array, $offset, $length);

    Please note that when using these functions, all references to these elements disappear. If you want to leave a key in the array but associate it with an empty value, assign the desired element to an empty string:

    $array = $array["foo"] = "";

    It is important to understand that the function unset() removes the element, while assigning "" to the element does not remove it, but does make its value equal to the empty string.

    If you work with numbers, it would probably be better to associate the value 0 with such a key.

    Let's say, if a company has stopped producing parts for the HBL-568 model, then a change can be made to the parts array:

    Unset($products["HBL-568"]);

    If the HBL-568 part is not in stock only temporarily and is expected to arrive from the factory, then it is better to do otherwise:

    $products["HBL-568"] = 0;

    The next point to understand is that when calling a function unset() for an array element, PHP adjusts the array so that the loop still works correctly.

    In other words, the array is not compressed to fill the resulting “holes”. Essentially, this means that all arrays are associative, even if they appear to be numeric at first glance. Let's look at clear examples to illustrate this behavior:

    // Create a "numeric" array $animals = array("ant", "bee", "cat", "dog", "elk", "fox"); print $animals; // Prints "bee" print $animals; // Prints "cat" count($animals); // Returns 6 // unset() unset($animals); // Removes an element $animals = "bee" print $animals; // Doesn't output anything and gives an error E_NOTICE print $animals; // Prints "cat" count($animals); // Returns 5 while the $array element remains in place and contains "fox" // Adding a new element $animals = "gnu"; // Adds a new element print $animals; // Doesn't print anything, also gives an error E_NOTICE print $animals; // Prints "gnu" count($animals); // Returns 6 // Assigning "" (empty string) $animals = ""; // Set to "empty string" print $animals; // Prints "" count($animals); // Returns 6, i.e. takes into account the empty array element when counting

    To get to a densely populated numeric array, use the function array_values():

    $animals = array_values($animals);

    Also, the array_splice() function automatically reindexes arrays to eliminate “holes”:

    // Create a "numeric" array $animals = array("ant", "bee", "cat", "dog", "elk", "fox"); array_splice($animals, 2, 2); print_r($animals);

    At the output we get:

    Array ( => ant => bee => elk => fox)

    Where might this feature come in handy?

    Let's say you are working with an array as a queue and want to remove elements from this queue without losing the possibility of random access, when you could accidentally fall into one of the resulting "holes".

    And finally, to safely remove the first or last element from an array, the functions array_shift() And array_pop() respectively.

    Everything is very simple with them:

    $stack = array("orange", "banana", "apple", "raspberry"); $fruit = array_shift($stack); print_r($stack);

    As a result of executing the code above, we will get the following output:

    Array ( => banana => apple => raspberry)

    To remove the last element, use the function array_pop():

    $stack = array("orange", "banana", "apple", "raspberry"); $fruit = array_pop($stack); print_r($stack);

    The output is the following array printout:

    Array ( => orange => banana => apple)

    That's all. We have discussed the main points on deleting array elements in PHP. If anything happens, the official documentation is always helpful.

    Did you like the material and want to thank me?
    Just share with your friends and colleagues!


    See also:

    PHP arrays are used everywhere. Adding and changing values ​​is usually straightforward.

    Removing array elements is a special operation. You can simply delete the element, or you can delete it and use it. This nuance provides great opportunities.

    PHP Arrays

    PHP is a modern programming language, the functionality in terms of working with arrays is performed at a high level. The programmer has the opportunity to use regular and associative arrays, design multidimensional data structures, and have a value of any type as array elements.

    There is a developed set of functions for working with arrays and special syntactic constructions. It is possible to traverse the array using your own algorithm and assign your own processing functions.

    Examples of creating and using an array

    The scPrint function is auxiliary. It recursively writes an array into a character string to demonstrate the results it produces.

    The $aFruits array is created in the usual way: the values ​​are listed, the indexes are assigned automatically from scratch. The last comma is irrelevant and does not create another empty element.

    The $aData array is created empty, then values ​​are added to it. Three are automatic, and two are with associative indexes that do not affect the overall numbering of values. Thus, the elements “plum” and “peach” have the indices “new” and “fresh”, respectively.

    The $aInfo array is multidimensional and associative.

    Three deletion operations show how to remove an element in a PHP array.

    The first operation removes the second element from the $aFruits array, its index is 1. It should be noted that the following indices are not shifted, which means that in cyclic operations with such an array it is necessary to check the existence of the element.

    The second operation deletes the last and first elements in the $aData array, which confirms that the deletion does not affect the indexes and the possibility of simultaneously deleting several elements.

    The third one deletes an array within an array and an element within an array that is part of another array.

    Normal removal of elements - unset

    The unset function removes. No matter what. It could just be a variable or an array element. unset() is considered to be a language operator, not a function. This operator does not return any value, and it “destroys” what is passed to it as parameters. The variable or array disappears as if it never existed.

    In PHP, you can remove empty array elements in different ways; in fact, what is considered an empty element depends on the programmer. However, it is not very wise to use multiple parameters in the unset() operator for this purpose. It is more practical to move group operations into group functions.

    Modern computers are very fast, and PHP is very fast. But this is not a reason to create and process tons of information using cumbersome algorithms; this is an objective reason to approach the process of removing array elements in progressive ways.

    Removing elements using string methods

    In PHP, you can remove empty array elements in bulk by converting the array to a string and returning it back. But this case is only suitable for really empty elements, missing indexes, or for the purpose of reindexing an array.

    The concept of an empty element depends on the task. Often an existing array element that contains certain information becomes empty. For example, an array records visitors. The array element contains:

    • visitor arrival time;
    • current operating mode;
    • active page;
    • last action time.

    If the difference between the time of arrival and the time of the last action is more than 1 minute (or another value), we can assume that the client has left the site. Records about such clients can be deleted if the task is to monitor the list of active visitors and not use more advanced methods using JavaScript.

    However, the "line" processing is good. For example, in PHP you can remove duplicate array elements like this:

    Fast and affordable way. It is not necessary to use the symbols "[" and "]" to denote each element, but remember that when transforming an array into a string, you must ensure that each element is unique. The framing characters should be chosen based on the characters that are allowed in the element. An unshakable rule: each array element in a row is unique and has its place (otherwise nothing can be returned back).

    This method is more convenient when the task in PHP is to remove an array element by value. You can use the array_flip function and swap the values ​​and keys, then do a classic unset. You can use the array_search function and find the key of the value you want to remove. But the lowercase version of the solution is clearer and simpler.

    PHP practically does not limit the developer in anything: neither in the number of dimensions, nor in the sizes of elements. There is no point in getting involved in this. Each element should be of the minimum possible length, and the number of dimensions should tend to one.

    If the number of array dimensions is more than three, this is a good reason to reconsider the decision. If an array element is longer than 4000-8000 characters, doubts should arise about the reasonableness of the constructed data picture.

    This opinion does not arise from the context of the functionality of a PHP array: remove an element, add an object of a different type, change one thing to something completely different. Simplicity is the key to success not only in life, but also in the algorithm. The program should work, and not surprise with its dimensions, dimensions and scale of ideas. It's the result that matters, not the big idea.

    As a modern programming language, PHP does not ignore recursion and the stack. It is fundamentally unimportant what the programmer means when he uses the array_pop() function in PHP: remove the last element of the array or simply get it into some variable.

    But keep in mind that in this context, the array_pop function is a push & pop function, that is, it is a stack tool, not a delete tool.

    Here it is customary to say not “delete”, but “extract”. The semantics are significantly different. However, the array_shift() function in PHP - removing the first element of an array or extracting it - has a different connotation. Here also the element is retrieved into an external variable and will not be in the array, but the indices are shifted.

    When the first element is extracted from an array, all elements that follow it are shifted forward, but only the numeric indices change; the lowercase indices remain unchanged.

    Delete or change: transaction history

    A variable is a very long time ago, an array is a long time ago, an object is yesterday. Object-oriented programming is still only talked about, but nothing is used to its full potential. It is a rare case when superficial solutions became the subject of enthusiastic solutions and “wise” content management systems (CMS) with a lot of “body”.

    Objective rule: it’s not the quantity of code that matters, but its quality! But no modern CMS has yet heeded this rule. Its authors believe that they are doing the right thing and know what they are doing.

    Result (characteristic feature): none of the modern CMS is distinguished by a decent “figure” (slenderness and lightness of designs), all have an immense completeness of code, each demands respect:

    • highly qualified programmer;
    • needs installation;
    • imposes hosting requirements;
    • creates difficulties when moving to another hosting;
    • really slows down work and administration.

    Programmers have been coming to the concept of rollback for a very long time; modern programming cannot imagine creating software without two functions:

    • undo;
    • redo.

    It is not only human nature to make mistakes, but in any situation there must be a rollback. In modern Internet programming tools to this day, this point not only does not matter, but is also used on a very limited scale.

    PHP operations on an array: removing an element, changing its type or adding something new are clear. But before there were variables, then arrays, then objects. Isn't there a reason to think about the fact that an array is just a variable over time?

    An array is a data structure over time. No language to this day considers time as a factor in syntax. You don’t even have to talk about semantics: from ancient times to this day, programmers and users understand only files and folders. The maximum that development has come to, for example, in PHP, the namespace is trivially reflected in the structure of folders and files.

    In this context, banal actions in PHP on an array: removing an element, changing or adding - require additional actions from the programmer. You can leave everything as it is, and it will work out as always. You can take into account every operation on data and record it in full, create and store a history of operations.

    This will be a completely different level of work and a radically better quality of the result.