Showing posts with label PHP Functions. Show all posts
Showing posts with label PHP Functions. Show all posts

Wednesday 18 May 2016

How to add element to array in php?

how to add element to array in php?

Question: How to add element to array?
$arrayData = array(0=>'one',1=>'two',3=>'three'); 
print_r($arrayData);
/*
 Array ( [0] => one [1] => two [3] => three ) 
 */
$arrayData['4']='four';


print_r($arrayData);
/**
Array ( [0] => one [1] => two [3] => three [4] => four ) 
 * 
 */



Question: How to add multiple element in array?
$arrayData = array(0=>'one',1=>'two',3=>'three'); 
print_r($arrayData);
/*
 Array ( [0] => one [1] => two [3] => three ) 
 */
$arrayData['4']='four';
$arrayData['5']='five';


print_r($arrayData);
/**
Array ( [0] => one [1] => two [3] => three [4] => four [5] => five ) 
 * 
 */



Question: How to replace multiple array element with single array?
$arrayData = array(0=>'one',1=>'two',3=>'three',4=>'four',5=>'five',6=>'six'); 
print_r($arrayData); echo "
";
/*
 * Array ( [0] => one [1] => two [3] => three [4] => four [5] => five [6] => six ) 
 */
array_splice($arrayData, 1,2,array('r'=>'replaced'));


print_r($arrayData);
/**
Array ( [0] => one [1] => replaced [2] => four [3] => five [4] => six ) 
 * 
 */



Question: How to add element to an begining of array?
$arrayData = array(0=>'one',1=>'two',3=>'three'); 
print_r($arrayData);
/*
Array ( [0] => one [1] => two [3] => three )  
 */
array_unshift($arrayData, "four", "five");


print_r($arrayData);
/**
Array ( [0] => four [1] => five [2] => one [3] => two [4] => three ) 
 * 
 */



Question: How to add elements at the end of array?
$arrayData = array(0=>'one',1=>'two',3=>'three'); 
print_r($arrayData);
/*
Array ( [0] => one [1] => two [3] => three )  
 */
array_push($arrayData, "four", "five");


print_r($arrayData);
/**
Array ( [0] => four [1] => five [2] => one [3] => two [4] => three ) 
 * 
 */



Tuesday 17 May 2016

How to delete an array elements?

How to delete an array elements?

Question: How to delete an array element based on key?
$arrayData = array(0=>'one',1=>'two',3=>'three',4=>'four',5=>'five',6=>'six'); 
print_r($arrayData); echo "
";
/*
 * Array ( [0] => one [1] => two [3] => three [4] => four [5] => five [6] => six ) 
 */
unset($arrayData[4]);


print_r($arrayData);
/**
Array ( [0] => one [1] => two [3] => three [5] => five [6] => six ) 
 * 
 */



Question: How to delete multiple array element?
$arrayData = array(0=>'one',1=>'two',3=>'three',4=>'four',5=>'five',6=>'six'); 
print_r($arrayData); echo "
";
/*
 * Array ( [0] => one [1] => two [3] => three [4] => four [5] => five [6] => six ) 
 */
array_splice($arrayData, 1,2);


print_r($arrayData);
/**
Array ( [0] => one [1] => four [2] => five [3] => six ) 
 * 
 */



Question: How to replace multiple array element with single array?
$arrayData = array(0=>'one',1=>'two',3=>'three',4=>'four',5=>'five',6=>'six'); 
print_r($arrayData); echo "
";
/*
 * Array ( [0] => one [1] => two [3] => three [4] => four [5] => five [6] => six ) 
 */
array_splice($arrayData, 1,2,array('r'=>'replaced'));


print_r($arrayData);
/**
Array ( [0] => one [1] => replaced [2] => four [3] => five [4] => six ) 
 * 
 */



Question: How to delete First element of an array?
$arrayData = array(0=>'one',1=>'two',3=>'three',4=>'four',5=>'five',6=>'six'); 
print_r($arrayData); echo "
";
/*
 * Array ( [0] => one [1] => two [3] => three [4] => four [5] => five [6] => six ) 
 */
array_shift($arrayData);


print_r($arrayData);
/**
Array ( [0] => two [1] => three [2] => four [3] => five [4] => six ) 
 * 
 */



Question: How to delete Last element of an array?
$arrayData = array(0=>'one',1=>'two',3=>'three',4=>'four',5=>'five',6=>'six'); 
print_r($arrayData); echo "
";
/*
 * Array ( [0] => one [1] => two [3] => three [4] => four [5] => five [6] => six ) 
 */
array_pop($arrayData);


print_r($arrayData);
/**
Array ( [0] => one [1] => two [3] => three [4] => four [5] => five ) 
 * 
 */



Wednesday 16 March 2016

How to convert a negative number to positive Number in PHP

How to convert a negative number to positive Number in PHP

Question: How to convert a negative number to positive Number in PHP?
$converToPostive= abs(-10.2); // 10.2 
$converToPostive=abs(10.2);   //10.2

(If number is already POSITIVE, It will remain the POSITIVE)


Question: How to convert a Positive Number to Negative Number in PHP?
$converToNegative =-1 * abs(10.2); //-10.2
$converToNegative =-1 * abs(-10.2); //-10.2

(If number is already NEGATIVE, It will remain the NEGATIVE)


Question: How to convert a negative number to positive Number and Vice Versa?
echo -1 * -10.2 //10.2
echo -1 * 10.2; //-10.2

(If number is NEGATIVE then convert to POSITIVE else if number is POSITIVE then convert to NEGATIVE)


Question: How to remove the decimal part from number?
$no=10.2
$noArray = explode('.',$no);
$no=$noArray[0]; //10

$no=-10.2;
$noArray = explode('.',$no);
echo $no=$noArray[0]; //-10

(just Remove the decimal part)


Question: How to get next highest integer value by rounding up?
echo ceil(10.2);    // 11
echo ceil(10.2222);  // 11
echo ceil(-10.22);  // -10
(Remove the decimal part and get next Highest Integer number)


Question: How to get next lowest integer value by rounding down?
echo floor(10.2);    // 11
echo floor(10.2222);  // 11
echo floor(-10.22);  // -10
(Remove the decimal part and get next lowest Integer number)


Question: How to rounding off a number?
echo round(10.4);  // 10
echo round(10.5);  // -11
echo round(10.6);  // -12
(Just rounding off the number)


Tuesday 19 January 2016

PHP 7 new features

PHP 7 new features

Following are PHP 7 new features

  1. Scalar type declarations: In this we can declare what type of argument will be accepted by functions.
    function sumOfInts(int ...$all_ints){ /** It will accept only integers **/
        return array_sum($all_ints);
    }
    echo sumOfInts(2, 3); //5
    echo sumOfInts(2, '3', '5'); //10
    echo sumOfInts(2, '3', 'string'); //Error: Uncaught TypeError: Argument 3 passed to sumOfInts() must be of the type integer, string given
    
  2. Return type declarations : In this we can declare what what will be the datatype from functions.
    function sumOfInts(int ...$all_ints):int
    {
        return array_sum($all_ints);
    }
    echo sumOfInts(2, 3); //5
    echo sumOfInts(2, '3', '5'); //10
    
    Here if function "sumOfInts" return an string OR Array, it will give error.
  3. Null coalescing operator (??) have been added.
    $userId = $_GET['user_id'] ?? '0';
    is equivalent to
    $userId = isset($_GET['user_id']) ? $_GET['user_id'] : '0';
  4. Spaceship operator :The spaceship operator is used for comparing two expressions. It returns -1, 0 or 1
    echo 1 <=> 1; // 0
    echo 1 <=> 2; // -1
    echo 2 <=> 1; // 1
    
  5. define() updates: Now you can add array.
    define('CLIENTS', [
        'client 1',
        'client 2',
        'client 3'
    ]);
    
    echo CLIENTS[1];//client 2
    
  6. Unicode codepoint escape syntax
    echo "\u{aa}";
    echo "\u{9999}";
  7. Closure::call Temporarily binding an object scope to a closure and invoking it.
    class A {private $x = 1;}
    $getX = function() {return $this->x;};
    echo $getX->call(new A);
  8. unserialize updates: Provide better security when unserializing objects on untrusted data and prevents possible code injections by enabling the developer to whitelist classes that can be unserialized.
    $data = unserialize($searilizedData, ["allowed_classes" => ["MyClass", "MyClass2"]]);
  9. list() function updates: Now list() can unpack the object also. Earlier it unpack int, float, string and array only.
  10. session_start() function updates:
    Now you can pass array-options in this function. For Example:
    session_start([
        'cache_limiter' => 'private',
        'read_and_close' => true,
    ]);
  11. intdiv() new function It performs an integer division of its operands and returns it. For Example:
    echo intdiv(100, 3); //33
  12. use updations Classes, functions and constants being imported from the same namespace can now be grouped together in a single use statement Below both are Same.
    use some\namespace\ClassA;
    use some\namespace\ClassB;
    use some\namespace\ClassC as C;
    OR
    use some\namespace\{ClassA, ClassB, ClassC as C};
  13. CSPRNG Functions i.e. random_bytes() and random_int()
    $bytes = random_bytes(5);
    var_dump(bin2hex($bytes)); //string(10) "385e33f741"
    var_dump(random_int(1, 100));//1-100
  14. Generator delegation: Generators can now delegate to another generator using yield, Traversable object/array automatically.
    function func1()
    {
        yield 1;
        yield 2;
        yield from func2();
    }
    
    function func2()
    {
        yield 3;
        yield 4;
    }
    
    foreach (func1() as $val)
    {
        echo $val, PHP_EOL;
    }
    /** Output 
    1
    2
    3
    4
    Output **/
    

Friday 2 October 2015

What is session_set_cookie_params

What is session_set_cookie_params

void session_set_cookie_params ( int $lifetime [, string $path [, string $domain [, bool $secure = false [, bool $httponly = false ]]]] )
Set the session cookie parameters

Its parameters defined in the php.ini file. The effect of this function only lasts for the duration of the script. Thus, you need to call session_set_cookie_params() for every request and before session_start() is called.

Following are Parameters
  1. lifetime: Lifetime of the session cookie, defined in seconds.
  2. path: Path on the domain where the cookie will work. Use a single slash ('/') for all paths on the domain.
  3. domain: Cookie domain, for example www.example.com. To make cookies visible on all subdomains then the domain must be prefixed with a dot like '.example.com'.
  4. secure If TRUE cookie will only be sent over secure connections.
  5. httponly: If set to TRUE then PHP will attempt to send the httponly flag when setting the session cookie.
 
session_set_cookie_params(0,"/webapp/");
session_start();
5.2.0 The httponly parameter was added. 4.0.4 The secure parameter was added.

Thursday 1 October 2015

imagecreatefrompng - Create a new image from file or URL - PHP

imagecreatefrompng - Create a new image from file or URL - PHP

resource imagecreatefrompng ( string $filename )
Create a new image from file or URL
imagecreatefrompng() returns an image identifier representing the image obtained from the given filename

<?php

function LoadPNG($imgname)
{
    
/* Attempt to open */
    
$im = @imagecreatefrompng($imgname);

    
/* See if it failed */
    
if(!$im)
    {
        
/* Create a blank image */
        
$im  imagecreatetruecolor(15030);
        
$bgc imagecolorallocate($im255255255);
        
$tc  imagecolorallocate($im000);

        
imagefilledrectangle($im0015030$bgc);

        
/* Output an error message */
        
imagestring($im155'Error loading ' $imgname$tc);
    }

    return 
$im;
}
header('Content-Type: image/png');$img LoadPNG('bogus.image');imagepng($img);imagedestroy($img);?>


PHPで画像を縮小してアップロードする
Make sure GD Library is enabled and "PNG Support" is must enabled in GD Library.

Wednesday 30 September 2015

count_chars - Count Number of character of string with PHP

count_chars - Count Number of character of string with PHP

mixed count_chars ( string $string [, int $mode = 0 ] )
Return information about characters used in a string
Mode value can have 0-5 and return following results
  1. 0 - Return an array with the byte-value as key and the frequency of every byte as value.
  2. 1 - same as 0 but only byte-values with a frequency greater than zero are listed.
  3. 2 - same as 0 but only byte-values with a frequency equal to zero are listed.
  4. 3 - a string containing all unique characters is returned.
  5. 4 - a string containing all not used characters is returned.



Counts the number of occurrences of every byte-value (0..255) in string and returns it in various ways.

<?php
$data 
"Two Ts and one F.";

foreach (
count_chars($data1) as $i => $val) {
   echo 
"There were $val instance(s) of \"" chr($i) , "\" in the string.\n";
}
?>


065 PHP من الألف إلى الياء Arabic التعامل مع النصوص Strings pt1

Tuesday 7 July 2015

Check if string contains specific words - PHP

Check if string contains specific words - PHP


strpos: Find the position of the first occurrence of a substring in a string.

strpos have 3 parameter and are following:
  1. haystack:The string to search in.
  2. needle:If needle is not a string, it is converted to an integer and applied as the ordinal value of a character.
  3. offset: It is optional, If provided then search will start this number of characters counted from the beginning of the string.
  4. The offset cannot be negative.

Note: It is case sensitive.


Different Examples of strpos
var_dump(strpos('web technology experts','web'));//int(0)
var_dump(strpos('web technology experts','technology'));//int(4)
var_dump(strpos('web technology experts','Technology'));//int(4)
var_dump(strpos('web technology experts','technology',4));//int(4)
var_dump(strpos('web technology experts','technology',5));//bool(false)
var_dump(strpos('web technology experts','expertss',6));//bool(false)


Saturday 20 June 2015

New features of PHP 5.5 with Examples


New features of PHP 5.5 with Examples


Following are 5.5 new features.

  1. Generators: has been added via the yield keyword.
    Generators provide an easy way to implement simple iterators.
    For Example:
     function xrange($start, $limit, $step = 1) {
        for ($i = $start; $i <= $limit; $i += $step) {
            yield $i;
        }
      }
      
      echo 'List of odd Numbers:';
      
      foreach (xrange(1, 9, 2) as $number) {
          echo "$number ";
      }
      
  2. finally: keyword added in try catch.
    In try catch, finally block will be called every time, regardless of whether an exception has been thrown or not.
    For Example:
        
        try {
        //write code here 
      }
      catch (Exception $e) {
          //Exception comes here
      }
      finally {
          echo "I am called everytime";
      } 
  3. New password hashing API
    Password hashing API that makes it easier to securely hash and manage passwords using the same crypt() in PHP has been added.
  4. foreach now supports list()
    Now in PHP5.5, You can use list function inside foreach function.
    See Example
     $listArray = [
        [10, 20],
        [30, 40],
        [50, 60],
    ];
    
    foreach($listArray as list($a, $b)) {
        echo "A: $a; B: $b";
    } 
  5. empty() supports expressions
    Now you can use expression in empty function.
    For Example:
      if(!empty(2*3)){
        echo "Its working";
        }
  6. Array and String literal dereferencing.
    String and Array can now be dereferenced directly to access individual elements OR characters.
    For Example
    echo 'Array dereferencing: ';
      echo [10, 02, 30][0];//10
      echo "\n";
      
      echo 'String dereferencing: ';
      echo 'Web Technology'[0]; //W
        
  7. Class name resolution via ::class
    ClassName::class to get a fully qualified name of class ClassName.
    For Example
    namespace Foo;
      class Bar {}
       
      echo Bar::class;
  8. OPcache extension added
    The Zend Optimiser+ opcode cache has been added to PHP5.5 as the new OPcache extension.
  9. foreach now supports non-scalar keys. For non-scalar keys, an Iterator must be used as they cannot occur in native PHP array.
  10. Apache 2.4 handler supported on Windows
  11. Improvements to GD Library.