In Java, we can use indexOf
and lastIndexOf
. Since those functions don\'t exist in PHP, what would be the PHP equivalent of this Java code?
<
<?php
// sample array
$fruits3 = [
"iron",
1,
"ascorbic",
"potassium",
"ascorbic",
2,
"2",
"1",
];
// Let's say we are looking for the item "ascorbic", in the above array
//a PHP function matching indexOf() from JS
echo(array_search("ascorbic", $fruits3, true)); //returns "2"
// a PHP function matching lastIndexOf() from JS world
function lastIndexOf($needle, $arr)
{
return array_search($needle, array_reverse($arr, true), true);
}
echo(lastIndexOf("ascorbic", $fruits3)); //returns "4"
// so these (above) are the two ways to run a function similar to indexOf and lastIndexOf()
In php:
stripos() function is used to find the position of the first occurrence of a case-insensitive substring in a string.
strripos() function is used to find the position of the last occurrence of a case-insensitive substring in a string.
Sample code:
$string = 'This is a string';
$substring ='i';
$firstIndex = stripos($string, $substring);
$lastIndex = strripos($string, $substring);
echo 'Fist index = ' . $firstIndex . ' ' . 'Last index = '. $lastIndex;
Output: Fist index = 2 Last index = 13
You need the following functions to do this in PHP:
strpos Find the position of the first occurrence of a substring in a string
strrpos Find the position of the last occurrence of a substring in a string
substr Return part of a string
Here's the signature of the substr
function:
string substr ( string $string , int $start [, int $length ] )
The signature of the substring
function (Java) looks a bit different:
string substring( int beginIndex, int endIndex )
substring
(Java) expects the end-index as the last parameter, but substr
(PHP) expects a length.
It's not hard, to get the desired length by the end-index in PHP:
$sub = substr($str, $start, $end - $start);
Here is the working code
$start = strpos($message, '-') + 1;
if ($req_type === 'RMT') {
$pt_password = substr($message, $start);
}
else {
$end = strrpos($message, '-');
$pt_password = substr($message, $start, $end - $start);
}
This is the best way to do it, very simple.
$msg = "Hello this is a string";
$first_index_of_i = stripos($msg,'i');
$last_index_of_i = strripos($msg, 'i');
echo "First i : " . $first_index_of_i . PHP_EOL ."Last i : " . $last_index_of_i;