PHP Coding Tips

Showing posts with label array. Show all posts
Showing posts with label array. Show all posts

Thursday, March 28, 2013

Sample smarty loop with images

If you want to print several images on your site, you must assign array of those images to smarty variable. Then, you can iterate over this array in smarty and show img tags for each image. Rember about good path:{foreach from=$sm_photos item=item} <img src="/content/photophoto/1/{$item.file}"> {/foreach}If your path will not target image file, you can get 404 error, but typically image will be just hidden

Thursday, March 21, 2013

PHP: Get last element of array

Often you need to get the last element of PHP array. This is easy to achieve with using count() function, wich counts all elements in array. Because PHP arrays are indexed from 0, you must remeber to get "count()-1" element of an array, not "count()" element:$exampleArray = array( 3,6,8,11,14 ); $lastElement = $array[ count($exampleArray) - 1]; echo $lastElement; // prints 14This is the obvious way for some begginer developers. But more experienced developers will know, that there is a function defined especially for this purpose: echo end( $exampleArray ); // prints 14 Because this function will move internal array pointer to the end, you can reset it if you are currently iterating over this orray, for example: reset( $exampleArray ); // prints 14 If you are afraid about non set array, or set as other type than array, you can use function is_array() to check if this variable is defined as array. You can also get a last key of an array in several ways: echo end(array_keys( $exampleArray) ); // or: end( $exampleArray ); echo key( $exampleArray ); If you don't want to move internal array pointer, you can use another one-liner to get last element from array: $last = array_slice($array, -1, 1, true);

Wednesday, March 20, 2013

How to do SMARTY foreach loop to present array values from PHP?

SMARTY is a very good template engine that helps you decompose application view and model. If you want to create a SMARTY foreach loop, you need to have assigned array first. If you want only to present array values, then it can be a usual PHP array without special keys. But SMARTY foreach, same as foreach in PHP, can present keys for array items. The basic construction of foreach loop in smarty, together with PHP array assigment to present in view, you can see below: // In PHP: $array = new array( 'key1' => 'val1' , 'key2' => 'val2' ); $smarty->assign('someAssignedArray' , $array ); // In SMARTY: {foreach from=$someAssignedArray key=keyOfItem item=itemValue} The key of this item is: {$keyOfItem}<br> The value of this item is: {$itemValue}<br> {/foreach}As you can see, we have to have defined array first. Example above shows custom keyed array, but this array can also have standarized default keys like 0,1,2,3,4 etc. The first step is to assign our array to SMARTY variables, because SMARTY doesn't have access to global PHP scope in nice way. So we must define a custom name for this variable -in example above i named it 'someAssignedArray'. So, the array wich in PHP exeist as $array, will exist in smarty as $someAssignedArray.
Now, you can write a foreach loop in your tpl file. The basic atribute of SMARTY foreach tag is from. This attribute says, from wich array you want to pick up all items for iteration. Remeber that this variable must have a dollar sign at begining.
Second required parameter in this loop construction is item. Item refers to name of variable, wich will have a value from array inside the loop. Key attribute works in the same way - it will contains key for item value in single loop iteration. There is some important thing - remeber that you create a new SMARTY varaibles here, so do not use dollar sign.
Inside the foreach loop, you can access your array item value and key by varaible names you specified as foreach tag attributes, this time begininnig with a dollar sign.
Of course, if yours item value is an array, nothings stop you to provide a nested foreach loop, with new key and value variables. This is useful thing.
If you want to print your array in fastest way, only for debug etc. you can try to use print_r function in your SMARTY tpl file. I wrote some nice tutorial about using print_r in SMARTY, so check itd.
If you want to provide additional filtering when iterating over items, see my tutorial about modifiers here.

Friday, August 17, 2012

Get last element of an array in PHP

To get last element of an array just use end() function. First idea can by get a index at count()-1 but remember that php arrays are associative arrays, so you can grab last element just by number.$lastElement = end($array); As simple as you see. It works even if your indexes are strings like 'name','surname' etc.

How to get size of an array in PHP (count elements) ?

To count elements and grab size of an array in php just use a count function:$elementsNumber = count( $array ); This will return a number of elements that are set in array

Get random element from an array in PHP

This tutorial will show you how to get a random element from an array in PHP. We will use mt_rand function and count to determine minimal and maximal index of a array. Remeber that arrays are indexed from 0, so if you have a ten elements array, the elements have indexes from 0 to 9. So, we need a random number that will by at least 0 but smaller than 10. Wi will user mt_rand function te generate that number. Se example how to use count and mt_rand to get random element from an array:$array = array( 1,2,3,4,5 ); echo $array[mt_rand(0,count($array)-1)]; As you can see we have to substract 1 from the size of an array. Also we use faster and better function mt_rand, because rand is slower and less randomness.

PHP Print array - how to show contents of an array

You can simple show entire contents of an array by callind print_r function:print_r($theArray); $arrayContents = print_r($theArray,true); Second example show how you can grab output to a variable to parse it or store somewhere (lika a file)

PHP Array add element - how to append element to an array

If you have a PHP array and wants to add element to it, you can do it just in this way:$myArray[] = 'new element'; This will add element to php array at its end

Friday, August 10, 2012

How to randomize array in PHP ?

If you want to random order of elements in your php array, use shuffle function:$somethings = array(); $somethings[0] = "element1"; $somethings[1] = "element2"; $somethings[2] = "element3"; shuffle( $somethins );Notice that this will modify that array wich you put as a argument (pass by reference)

How to add element to an array ?

If you want how to add or append element to a PHP array, see this code snippet:$somethings = array(); $somethings[] = "element"; // append as last element $somethings[4] = "other element"; $somethings['thekey'] = "some other element";

Wednesday, August 8, 2012

Multiple checkboxes send to array as php

If you have bad experience with making inputs named like cat1,cat2,cat3, there is a way to post to php custom amount of elements within the same field name. If you add [] to your field name, this value will be posted to PHP script as array of values, and you can traverse array easily: Category 1 Category 1 Category 1 // in php: foreach( $_POST['selectedcategories'] as $cat ) { echo "User selected $cat !
"; }
Of course, you can generate inputs by php from some source selecion model

Tuesday, August 7, 2012

print_r in smarty - How to print your array contents in smarty template.

You can print a array contents like in php print_r() function in smarty tempalte. The common mistake is to forget about second print_r parametr for returning it's output. This parameter have to be set to true. If you forget to set it to true, your array contents propably will be somewhere at begining of a content. This is the solution:
{$myArray|@print_r:true}
Notice the @ symbol that provides parsing argument as array, not as string.

How to merge (join) two arrayis in PHP together ?

You can merge all elements of two and more arrays into one array by array_merger func:$summaricArray = array_merge( $firstPartArray , $secondPartArray );This results in all elements from both arrays in summaricArray

How to split an array to parts by comma or special character (string to array) ?

Use explode function for this job:$names = 'John,Margaret,Thomas'; $namesArray = explode( ',' , $names ); echo $namesArray[0]; echo $namesArray[1]; echo $namesArray[2];You can also use a character sequence to split string like a "splitplace"