Jump to content

in_array modification


knowram

Recommended Posts

I was not able to make that work. Really I think I am just looking for a way to see if a variable starts with specific letters.here is an example of what i am trying to do.

given $array1 = array('med:1','med:2','med:3','temp','start');

I would like to write a for loop something like this

[code]
for ($i = "0"; $i <= "4"; $i++){
  if ($arra1[$i] starts with "med:"){ //do something}
  else{ // do something different}
}
[/code]
Link to comment
https://forums.phpfreaks.com/topic/30837-in_array-modification/#findComment-142234
Share on other sites

Try something like this:

[code]
<?php
  $array1 = array('med:1','med:2','med:3','temp','start');

  foreach ($array1 AS $val) {
    if (preg_match('/^(med\:)/',$val)) {
      //do something here
    }
    else {
      //do something else here
    }
   
  }
?>

[/code]
Link to comment
https://forums.phpfreaks.com/topic/30837-in_array-modification/#findComment-142243
Share on other sites

I would do it like this:

[code]
<?php
/**
* @author: Nick Stinemates // keeb
* @description: Searches array for keys beginning with certain char's
*/

  $array1 = array('med:1','med:2','med:3','temp','start');

  foreach ($array1 AS $val) {
switch ($val) {
case strpos($val, "med:"):
//do something
break;
default:
//do something else
}
   
  }
?>
[/code]
Link to comment
https://forums.phpfreaks.com/topic/30837-in_array-modification/#findComment-142284
Share on other sites

The heck? Why are you using a switch when there's only two possibilities? Also, your code will trigger a false positive if the substring is somewhere in the string besides the first four letters.

[code]<?php

$array1 = array('med:1','med:2','med:3','temp','start');

foreach($array1 as $item){
if(strpos($item,"med:")===0){
//Note we used === instead of ==. false==0, but false!==0.
//Also note that using strpos instead of regular expressions is faster for simple searches like this.
//Do something
}
else{
//Do something else
}
}
?>[/code]
Link to comment
https://forums.phpfreaks.com/topic/30837-in_array-modification/#findComment-142307
Share on other sites

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.