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

Monday, 5 August 2019

PHP array functions

In this post , we will be discussing the php array functions. As with any other programming language,PHP has its own array functions

What is array: A array is the chain of values stored in single variable where values can be retrived based on there position in the array
$arr ={a,b,c,d,e,f};
There are three type of array in PHP
Indexed arrays – Arrays with numeric index
Syntax
$arr ={a,b,c,d,e,f};
The values are retrieved based on the numerical index
<?php
$arr ={a,b,c,d,e,f};
print “First element is $arr[0]”;
print “second element is $arr[1]”;
print “Third element is $arr[2]”;
print “Fourth element is $arr[3]”;
print “Fifth element is $arr[4]”;
?>
Associative arrays – Arrays with named keys
Syntax
array(key=>value,key=>value,key=>value,etc.);
$age = array (
Tom=>”34″,
rony=>”36″,
john=>”35″,
);
The values are retreived based on named keys
<?php
$age = array (
Tom=>”34″,
rony=>”36″,
john=>”35″,
);
print “Tom age is $age[Tom]”;
print “Rony age is $age[rony]”;
print “John age is $age[john]”;
?>
Multidimensional arrays – Arrays containing one or more arrays. The array contains multiple arrays
$house= array(
array ( a,b,c,d),
array ( 1,2,3,4),
array ( A,B,C,D)
)
The values are retreived based on two keys
<?php
$house= array(
array ( a,b,c,d),
array ( 1,2,3,4),
array ( A,B,C,D)
)
print ” First array and first element is $house[0][0]”;
print “First array and second element is $house[0][1]”;
print “second array and second element is $house[1][1]”;
print “Third array and second element is $house[2][1]”;
?>
How to count the elements in the array and retrive it dynamically
The count in a array can be done using the count function
count(array,mode);
<?php
$arr=array(“a”,”b”,”c”);
echo count($arr);
?>
We can loop through all the elements and print it
<?php
$test=array(“a”,”b”,”c”);
$arroflength=count($test);
for($x=0;$x<$arroflength;$x++)
{
echo $test[$x];
echo “<br>”;
}
?>

Important php array functions
sizeof($arr)  : It is same as count($arr).  It is use to count the members in the array  which then can be used in loop to process all the array element
<?php
$arr=array(“e”,”f”,”g”);
echo sizeof($arr);
?>
We can loop through all the elements and print it
<?php
$test=array(“e”,”f”,”g”);
$arroflength=sizeof($test);
for($x=0;$x<$arroflength;$x++)
{
echo $test[$x];
echo “<br>”;
}
?>
array_values($arrtest)  and array_keys($arrtest):
array_values  function accepts a PHP array and returns a new array containing only its values (not its keys). Its counterpart is the array_keys() function.
This can be use this function to retrieve all the values from an associative array.
array_keys  function accepts a PHP array and returns a new array containing only its keys.
This can be use this function to retrieve all the keys from an associative array.
<?php
$age = array (
Tom=>”34″,
rony=>”36″,
john=>”35″,
);
print_r(array_values($age));
?>
The above code will print array having the values
<?php
$age = array (
Tom=>”34″,
rony=>”36″,
john=>”35″,
);
print_r(array_keys($age));
?>
The above code will print array having the keys
array_unique($arraytest):
This function strip the duplicate data from the array
array_pop($arraytest)
This function removes the element from the  end of array
array_push($arraytest, $values)
This  function add the element stored in $values in the end to the array
array_shift($arraytest)
This function removes the element from the  start of array
array_unshift($arraytest, $values)
This  function add the element stored in $values in the start to the array

Friday, 2 August 2019

How to remove a specific value within an array using PHP

If you have an array and you wish to remove the “None” values in the array you can use the method below, please replace the “None” value with the value you need to remove from the array
$array = array("Apple","Orange","None"); //The array

//Removing all None values from the array
 
foreach (array_keys($array, 'none') as $key) {
 
    unset($array[$key]);
 
}

print_r($array); //This will output the array without the value None

How to check if an array contains a empty element or value

Use the following code example
$array = array('a','b',''); //The array to check for empty values
echo (in_array('  ', $array)) ? 'Empty values exists' :'No empty values'; ?> //Checking if empty values exist in the array
NOTE:
in_array = searches a array for a specific value

How to check for empty values within a array using PHP

If you have an array called $array with the below values
Array
(
    [0] => 1299016800
    [1] => 
    [2] => 
)
As we can see in the above example we have 2 empty values within the array, now how do we determine this using PHP
First we get the size of the array
$mainSize = sizeof($array);
Now we get the size of the array without the empty values
$emptySize =sizeof(array_filter($array));
Now we compare the 2 different sizes, if they are equal to each other, then it means that there aren’t empty values within the array, else there are empty values within the array
$mainSize = sizeof($array);
$emptySize =sizeof(array_filter($array));
 
if($mainSize == $emptySize){
              echo 'Array not empty';
}else{
              echo 'Array is empty';
}

Friday, 5 October 2018

PHP: Delete an element from an array

There are different ways to delete an array element, where some are more useful for some specific tasks than others.

Delete one array element

If you want to delete just one array element you can use unset() or alternative array_splice().
Also if you have the value and don't know the key to delete the element you can use array_search() to get the key.

unset() method

Note that when you use unset() the array keys won't change/reindex. If you want to reindex the keys you can use array_values() after unset() which will convert all keys to numerical enumerated keys starting from 0.
Code
<?php

    $array = array(0 => "a", 1 => "b", 2 => "c");
    unset($array[1]);
               //↑ Key which you want to delete

?>
Output
Array (
    [0] => a
    [2] => c
)

array_splice() method

If you use array_splice() the keys will be automatically reindexed, but the associative keys won't change opposed to array_values() which will convert all keys to numerical keys.
Also array_splice() needs the offset, not the key!, as second parameter.
Code
<?php

    $array = array(0 => "a", 1 => "b", 2 => "c");
    array_splice($array, 1, 1);
                       //↑ Offset which you want to delete

?>
Output
Array (
    [0] => a
    [1] => c
)
array_splice() same as unset() take the array by reference, this means you don't want to assign the return values of those functions back to the array.

Delete multiple array elements

If you want to delete multiple array elements and don't want to call unset() or array_splice() multiple times you can use the functions array_diff()or array_diff_key() depending on if you know the values or the keys of the elements which you want to delete.

array_diff() method

If you know the values of the array elements which you want to delete, then you can use array_diff(). As before with unset() it won't change/reindex the keys of the array.
Code
<?php

    $array = array(0 => "a", 1 => "b", 2 => "c");
    $array = array_diff($array, ["a", "c"]);
                              //└────────┘→ Array values which you want to delete

?>
Output
Array (
    [1] => b
)

array_diff_key() method

If you know the keys of the elements which you want to delete, then you want to use array_diff_key(). Here you have to make sure you pass the keys as keys in the second parameter and not as values. Otherwise you have to flip the array with array_flip(). And also here the keys won't change/reindex.
Code
<?php

    $array = array(0 => "a", 1 => "b", 2 => "c");
    $array = array_diff_key($array, [0 => "xy", "2" => "xy"]);
                                   //↑           ↑ Array keys which you want to delete
?>
Output
Array (
    [1] => b
)
Also if you want to use unset() or array_splice() to delete multiple elements with the same value you can use array_keys() to get all the keys for a specific value and then delete all elements.



  // our initial array  
   $arr = array("blue", "green", "red", "yellow", "green", "orange", "yellow", "indigo", "red");  
  print_r($arr);

  // remove the elements who's values are yellow or red  
   $arr = array_diff($arr, array("yellow", "red"));
  print_r($arr);  
This is the output from the code above:
Array
(
    [0] => blue
    [1] => green
    [2] => red
    [3] => yellow
    [4] => green
    [5] => orange
    [6] => yellow
    [7] => indigo
    [8] => red
)

Array
(
    [0] => blue
    [1] => green
    [4] => green
    [5] => orange
    [7] => indigo
)
Now, array_values() will reindex a numerical array nicely, but will remove all key strings from the array and replace them with numbers. If you need to preserve the key names (strings), or reindex the array if all keys are numerical, use array_merge():
$arr = array_merge(array_diff($arr, array("yellow", "red")));
print_r($arr);
outputs
Array
(
    [0] => blue
    [1] => green
    [2] => green
    [3] => orange
    [4] => indigo
)



unset($array[$index]);



Also, for a named element:
unset($array["elementName"]);



<?php
    $stack = array("fruit1", "fruit2", "fruit3", "fruit4");
    $fruit = array_shift($stack);
    print_r($stack);

    echo $fruit;
?>
Output:
Array
(
    [0] => fruit2
    [1] => fruit3
    [2] => fruit4
)

fruit1



unset() destroys the specified variables.
The behavior of unset() inside of a function can vary depending on what type of variable you are attempting to destroy.
If a globalized variable is unset() inside of a function, only the local variable is destroyed. The variable in the calling environment will retain the same value as before unset() was called.
<?php
function destroy_foo() 
{
    global $foo;
    unset($foo);
}

$foo = 'bar';
destroy_foo();
echo $foo;
?>
The Answer of the above code will be bar
To unset() a global variable inside of a function
<?php
function foo() 
{
    unset($GLOBALS['bar']);
}

$bar = "something";
foo();
?>



If you need to remove multiple elements from an associative array, you can use array_diff_key() (here used with array_flip()):
$my_array = array(
  "key1" => "value 1",
  "key2" => "value 2",
  "key3" => "value 3",
  "key4" => "value 4",
  "key5" => "value 5",
);

$to_remove = array("key2", "key4");

$result = array_diff_key($my_array, array_flip($to_remove));

print_r($result);
Output:
Array ( [key1] => value 1 [key3] => value 3 [key5] => value 5 ) 



/*
 * Remove by value
 */
public function removeFromArr($arr, $val)
{
    unset($arr[array_search($val, $arr)]);
    return array_values($arr);
}



I'd just like to say I had a particular Object, that had variable attributes (it was basically mapping a table and I was changing the columns in the table, so the attributes in the object, reflecting the table would vary as well
class obj {
    protected $fields = array('field1','field2');
    protected $field1 = array();
    protected $field2 = array();
    protected loadfields(){} 
    // This will load the $field1 and $field2 with rows of data for the column they describe
    protected function clearFields($num){
        foreach($fields as $field) {
            unset($this->$field[$num]); 
            // This did not work the line below worked
            unset($this->{$field}[$num]); // You have to resolve $field first using {}
        }
    }
}
The whole purpose of $fields was just so I don't have to look everywhere in the code when they're changed, I just look at the beginning of the class and change the list of attributes and the $fields array content to reflect the new attributes.
Took me a little while to figure this out. Hope this can help someone.



$arr = array('orange', 'banana', 'apple', 'raspberry');
$result= array_pop($arr);
print_r($result);



<?php 
//If you want to remove a particular array element use this method
$my_array = array("key1"=>"value 1","key2"=>"value 2","key3"=>"value 3");

print_r($my_array);
if(array_key_exists("key1",$my_array)){  
unset($my_array['key1']);
print_r($my_array);
}else{
echo "Key does not exist";
}
?>

<?php 
//To remove first array element
$my_array = array("key1"=>"value 1","key2"=>"value 2","key3"=>"value 3");
print_r($my_array);
$new_array=array_slice($my_array,1); 
print_r($new_array);
?>


<?php 
echo "<br/> ";
//To remove first array element to length
//starts from first and remove two element 
$my_array = array("key1"=>"value 1","key2"=>"value 2","key3"=>"value 3");
print_r($my_array);
$new_array=array_slice($my_array,1,2); 
print_r($new_array);
?>
Output
 Array ( [key1] => value 1 [key2] => value 2 [key3] => 
 value 3 ) Array (    [key2] => value 2 [key3] => value 3 ) 
 Array ( [key1] => value 1 [key2] => value 2 [key3] => value 3 ) 
 Array ( [key2] => value 2 [key3] => value 3 )
 Array ( [key1] => value 1 [key2] => value 2 [key3] => value 3 ) 
 Array ( [key2] => value 2 [key3] => value 3 ) 



unset() multiple, fragmented elements from an array

While unset() has been mentioned here several times, it has yet to be mentioned that unset() accepts multiple variables making it easy to delete multiple, noncontiguous elements from an array in one operation:
// Delete multiple, noncontiguous elements from an array
$array = [ 'foo', 'bar', 'baz', 'quz' ];
unset( $array[2], $array[3] );
print_r($array);
// Output: [ 'foo', 'bar' ]

unset() dynamically

unset() does not accept an array of keys to remove, so the code below will fail (it would have made it slightly easier to use unset() dynamically though).
$array = range(0,5);
$remove = [1,2];
$array = unset( $remove ); // FAILS: "unexpected 'unset'"
print_r($array);
Instead, unset() can be used dynamically in a foreach loop:
$array = range(0,5);
$remove = [1,2];
foreach ($remove as $k=>$v) {
    unset($array[$v]);
}
print_r($array);
// Output: [ 0, 3, 4, 5 ]

Remove array keys by copying the array

There is also another practice that has yet to be mentioned. Sometimes, the simplest way to get rid of certain array keys is to simply copy $array1 into $array2.
$array1 = range(1,10);
foreach ($array1 as $v) {
    // Remove all even integers from the array
    if( $v % 2 ) {
        $array2[] = $v;
    }
}
print_r($array2);
// Output: [ 1, 3, 5, 7, 9 ];
Obviously, the same practice applies to text strings:
$array1 = [ 'foo', '_bar', 'baz' ];
foreach ($array1 as $v) {
    // Remove all strings beginning with underscore
    if( strpos($v,'_')===false ) {
        $array2[] = $v;
    }
}
print_r($array2);
// Output: [ 'foo', 'baz' ]



This may help...
<?php
    $a1=array("a"=>"red","b"=>"green","c"=>"blue","d"=>"yellow");
    $a2=array("a"=>"purple","b"=>"orange");
    array_splice($a1,0,2,$a2);
    print_r($a1);
    ?>
result will be:
Array ( [0] => purple [1] => orange [c] => blue [d] => yellow )



You can simply use unset() to delete an array.
Remember that array must be unset after foreach function.



unset don't change the index but array_splice does
$arrayName = array( '1' => 'somevalue',
                        '2' => 'somevalue1',
                        '3' => 'somevalue3',
                        500 => 'somevalue500',
                             );


    echo $arrayName['500']; 
    //somevalue500
    array_splice($arrayName, 1,2);

    print_r( $arrayName );
    //Array ( [0] => somevalue [1] => somevalue500 )



    $arrayName = array( '1' => 'somevalue',
                        '2' => 'somevalue1',
                        '3' => 'somevalue3',
                        500 => 'somevalue500',
                             );


    echo $arrayName['500']; 
    //somevalue500
    unset($arrayName[1]);

    print_r( $arrayName );
    //Array ( [0] => somevalue [1] => somevalue500 )