Useful PHP array functions

How to check if a value exists in array or not in PHP?

PHP function in_array() checks if a value exists in an array in a case-sensitive manner and returns boolean result.

e.g.,

<?php

$os = array(“Mac”, “NT”, “Unix”, “Linux”);

if (in_array(“Unix”, $os)) {

echo “Got Unix”;

}

?>

How to check if a key/index exists in array or not in PHP?

PHP function array_key_exists() checks if the given key or index exists in the array and returns boolean result

e.g.,

<?php

$search_array = array(‘first’ => 1, ‘second’ => 4);

if (array_key_exists(‘first’, $search_array)) {

echo “The ‘first’ element is in the array”;

}

?>

How to get all keys in an array in PHP?

PHP function array_keys() returns all the keys of an array

eg.,

In associative array/hash reference,

<?php

$array = array(0 => 100, “color” => “red”);

print_r(array_keys($array));

?>

It returns,

Array (

[0] => 0

[1] => color

)

In array reference,

<?php

$array = array(“blue”, “red”, “green”, “blue”, “blue”);

print_r(array_keys($array, “blue”)); //all indexes where value is blue

?>

It returns,

Array (

[0] => 0

[1] => 3

[2] => 4

)

How to get all values in an array in PHP?

PHP function array_values() returns all the values from the input array and indexes numerically the array.

eg.,

<?php

$array = array(“size” => “XL”, “color” => “gold”);

print_r(array_values($array));

?>

It returns,

Array

(

[0] => XL

[1] => gold

)

Array loops,

Apart from well known “for” and “foreach” loops, there another way to loop through the indexed/associative array,

<?php

$array = array(“value1″,”value2″,”value3″);

for(reset($array),current($array),next($array){

echo(“Element “.key($array).” contains “.current($array).”<br/>”;

}

//is the equivalent of…

for($i=0;$i<count($array);$i++){

echo(“Element $i contains $array[$i]<br/>”);

}

//It’s use is probably to save on the no. of variables used.

?>

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>